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

Java Basics Notes

The document provides an overview of Java, its development history, and key features, including the Java Virtual Machine (JVM) and Object-Oriented Programming (OOP) concepts. It explains the main pillars of OOP such as abstraction, encapsulation, inheritance, and polymorphism, along with Java's syntax, data types, and memory management. Additionally, it discusses constructors, Java's architecture, and type conversion methods, highlighting Java's platform independence and security features compared to C++.

Uploaded by

Anuj
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 views30 pages

Java Basics Notes

The document provides an overview of Java, its development history, and key features, including the Java Virtual Machine (JVM) and Object-Oriented Programming (OOP) concepts. It explains the main pillars of OOP such as abstraction, encapsulation, inheritance, and polymorphism, along with Java's syntax, data types, and memory management. Additionally, it discusses constructors, Java's architecture, and type conversion methods, highlighting Java's platform independence and security features compared to C++.

Uploaded by

Anuj
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

2026-01-14

09:35

Tags:

java-basics

Introduction:

Initiated by James Gosling


developed by SunMicroSystem in 1990s earlier called Green and later was renamed to java.
Currently owned by Oracle
JDK it stands for java development kit.
Its a combination of all tools related to java
It includes tools like:
1. JVM: Java Virtual Machine. It includes JRE which stands for Java Runtime Environment
2. JIT: Just in time compiler
there are three version of java:
1. JavaSE: desktop app development.
2. JAVAEE: for web dev and enterprise
3. JAVAME: for mobile and embedded systems

JVM:

The java virtual machine is an abstract computing machine that enables a computer to run java
programs. It acts as interpreter between java bytecode and the underlying operating system.

Role of JVM:

1. Loading class files


2. Verifying bytecode
3. managing memory
4. Executing program instructions.
5. Providing runtime environment.

Features of JAVA:

[Link]

Java works on the concept of WORA (write once run anywhere)


With the help of JVM, Java can run its code anywhere being platform independent
It is Memory safe.
Multithreading

OOP(object oriented programming):

Object oriented programming is a programming methodology in which software is developed by


organizing the program around objects and classes instead of functions and logic alone.
In OOP, a program is divided into small reusable component called objects, which represents real
world entity.

Class:
It is an user defined data type which represents the blueprint or template of an object.
consists of methods and data member
In java the main function is always public.
Logical Entity

Object:

Every objects holds a behavior and attribute.


Instance of a class. Real time entity.

Main pillars of OOP:

Abstraction:

It is the process of hiding internal implementation details and showing only essential features of an
object to the user.
in java we can create abstracted class using the abstract keyword.

Encapsulation:

It is the process of binding data and methods together into a single unit, called a class. It also
involves protecting data by restricting direct access using access modifiers.

Advantages of encapsulation:

1. Improves data security.


2. Controls data access
3. Makes program more flexible

Inheritance:

Inheritance is the mechanism by which one class acquires the properties and methods of another
class. The existing class is called superclass, and new class is called subclass

Advantages of inheritance:

Code reusability.
Faster development.
Improved program structure,
Reduced memory usage.

class Vehicle{
void start(){
[Link]("Vehicle starts");
}
}
class car extends Vehicle{
void speed(){
[Link]("Car speed is 80km\h ");
}
}

Polymorphism:
Polymorphism means one interface with multiple implementations. It allows a single method or
object to behave differently in different situations.
Can be done by two ways-
1. Method Overloading (Compile time polymorphism): In method overloading, multiple methods
have the same name but different parameters.
Compiling process is when we are converting into the bytecode
can change return type, sequence of parameters, number of parameters.
2. Overriding (Runtime polymorphism): In method overriding, a subclass provides its own
implementations of a method defined in the superclass
Runtime is when the code is converted into machine code and is executing

Basic Syntax:

class first{
public static void main(String[] args) {
[Link]("Hello World");
}
}

A class can be public, private and protected


By default it will be packaged protected while working with packages or else it will be public.
By default it will be less visible than public
static is used to define class-level member
We can use the keyword final if we don’t want to change the value
we use [Link] when we want the output. Similarly we can use [Link] for taking input
println we use this when we want to print on a new line. We can also use print printf as well but
using print and println is recommended
public can be accessed by anyone.
protected specific group can access that data.
private no one can directly access that class, Only inherited class can access the private data.
We cannot run the program without the main class.
Objects will always be created in main class
We use new to create an object/ new is used to initiate the memory

Operators in java:

Arithmetic:

Operator Name Example Usage

+ Addition a + b Adds two numbers

- Subtraction a - b Subtracts

* Multiplication a * b Multiplies

/ Division a / b Divides

% Modulus a % b Remainder

++ Increment a++ / ++a Increases by 1

-- Decrement a-- / --a Decreases by 1

Assignment operators:
Operator Example Meaning

= a = 5 Assign value

+= a += 3 a = a + 3

-= a -= 2 a = a - 2

*= a *= 4 a = a * 4

/= a /= 2 a = a / 2

%= a %= 2 a = a % 2

Relational (comparison ) operators:

Operator Example Usage

== a == b Equal to

!= a != b Not equal

> a > b Greater than

< a < b Less than

>= a >= b Greater or equal

<= a <= b Less or equal

Logical Operators:

used for logical conditions


There are three logical operator:
1. logical AND: &&
2. logical OR: ||
3. logical NOT: !

Memory types:

class xyz{
static String a = "hello";
int b = 10;

public void demo(){


int d = 20; // local variable
[Link]("Testing");
}
}
class variables{
public static void main(String[] args) {
xyz o = new xyz();
[Link]();
[Link](xyz.a);
}
}
1. Stack:

1. variable d will be stored in the stack


2. Method calls demo() will be stored in the stack as well
3. main function will be stored here
4. object reference variable o will be stored here as well

2. Heap:

1. Instance variable will be stored in the heap, here b


2. object will be stored in the heap
3. garbage collection will be done in heap
4. Stack and heap can communicate together with the help of object.
5. This memory is allocated dynamically and shared among all objects.

3. Method area:

1. Static variables and methods will be stored here. a will be stored here.
2. the code/logic inside the function demo() and the main()function will be stored here as well
3. stack and heap can access the method area.
4. Stores the class structure information
5. Stores Constant pool: It is a special memory area in which java stores constants and reusable values
6. This area is shared among all threads

Variables:

A variable is a named memory location used to store data whose value can be changed during the
program execution.
Java is an static language meaning the data type of the variable must be mentioned before
initialising.
only \$ and _ can be used at the start of the variable name.
There are three types of variables: Memory will be allocated differently for all three variables
1. Instance variable: allocates memory from heap, object calling works on heap. Each object will
have a copy of the instance variable
2. Static: allocates memory from stack, variables which are accessible all over the class are
stored in stack
3. Method level or local variable:
fastest execution is of: local variables
Stored in the stack memory
Access is direct and fastest
Scope limited to the function/block $\rightarrow$ no lookup needed

Local Instance Static

declared inside the method declared inside the class declared inside the class

Memory location is stack memory location is heap memory location is Method area

no default value default value is present default value is present

object is not required object is required no object is required

scope is only inside method scope is object level class level

object reference variable is also stored on stack.

we use static when we want to call a variable or a method without creating a new object for it.

coding example of variables:


class variableClass{
public static String name = "Anuj"; // static variable
int a;
int b;
void display(){
int c = 10; // local
[Link](c);
[Link](a + " " +b);
}
variableClass(int a, int b){
this.a =a;
this.b =b;
}
}
class variableTypes{
public static void main(String[] args) {
variableClass check = new variableClass(13,13);
[Link]();
}
}

With the help of this.1 we can reference to the instance variable.


here check will be a reference variable.

Data Types:

Primitive:

Integers:

1. byte = 8bits range: -128 to 127


2. short = 16bits range: -32768 to 32767
3. int = 4 byte, range: $-2{31} \text{ to} 2{31} -1$
4. long = 8 byte, range: $-2{63} \text{ to} 2{63} -1$

float - 4 bytes to forcefully convert a variable we can use f

range: $-3.4 \times 10{-38} \text{ to } 3.4 \times 10{38}$

double - 8 bytes similarly we can use d

range: $1.7 \times 10{-308} \text{ to } 1.7 \times 10{308}$

char

boolean

Non-Primitive:

1. String
2. Array
3. Class
4. interface
Difference between java and cpp:

Java CPP

Platform independent Platform dependent

Portable Not portable

more secure Less secure

Doesn’t support pointers Supports pointers

Purely object oriented programming It’s not purely OOP

Keywords:

Keywords are reserved words in java that have predefined meanings. These words are part of the java
language syntax and cannot be used as identifiers such as variable names, class names or method
names.
Java has 50+ keywords:
abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do,
double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int,
interface, long, native, new, package, private, protected, public, return, short, static, strictfp,
super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while, module,
requires, exports, opens, to, uses, provides, with, transitive, var, yield, record, sealed, non-sealed,
permits

[!NOTE] Const and goto are reserved but unused var, yield, record, sealed, non-sealed, permits are
contextual keywords true, false, nulls are literals not keywords

Constructors:

It is a special type of method by which we can create object.

We can initialize objects with the help of constructors

Cannot be overridden.

name of the class and the constructor should be the same

cannot be private, should be public

It is of three types:

1. Default constructor: This is the default constructor created when a class is created. Has body
2. Parameterised constructor: We can pass parameters by the help of this constructor.
3. Non-Parameterised constructor: When we dont have to pass any value. Doesn’t have body

Code example:

class student{

public void fun(){


[Link]("My name is anuj");
}
}
class studentName{
public static void main(String[] args) {
student testing = new student();
[Link]();
}
}

We create a variable with the class student.


Here new is used to intialize memory for the object.
student() here is the default constructor.
the name of the constructor and the class name should be the same

Coding example of parameterised constructor:

class student{
public String name;
public int roll;

student(String name, int roll){


[Link] = name;
[Link] = roll;
}

public void fun(){


[Link]("Details of student: ");
[Link](name);
}
}

class parameterConst{
public static void main(String[] args) {
student details = new student("Anuj", 12);
[Link]();
}
}

converting this to non parameterised constructor:

class student{
String name;
int roll;
long mob;
student(){
[Link]("Object has been created");
}
public void show(){
[Link]("The student name is "+name + " \nRoll number is " +
roll + " \nMobile number is " + mob );
[Link]("");
}
}
class nonparam{
public static void main(String[] args) {
student s1 = new student();
// [Link]();
student s2 = new student();
// [Link]();
student s3 = new student();
// [Link]();
student s4 = new student();
// [Link]();
student s5 = new student();
// [Link]();
}
}

The constructor will run every time an object is created.

Copy Constructor:

By the help of this constructor we can create a shallow copy of the object.
shallow copy means the data will be created at a new memory reference.
Hard copy means the memory location will be different for both the original and the copy
variable

class student{
String name;
static String testing = "hello";
int roll;
String add;

student(String name, int roll, String add){


[Link] = name;
[Link] = roll;
[Link] = add;
}

student(student s){
name = [Link];
roll = [Link];
add = [Link];
}
public void show(){
[Link](name);
[Link](roll);
[Link](add);
[Link]("");
}
}
class copyConst{
public static void main(String[] args) {
student s1 = new student("Anuj",1,"Moradabad");
[Link]();
student s2 = new student(s1);
[Link]();
[Link]([Link]);
}
}

student(student s) is the copy constructor


It accesses the object s and then copies it into the new object that we will create. s2 in the main
function.

JVM architecture:

[Link]

Class loader:

It is responsible for loading .class files into memory at runtime.


It is divided into three parts:
1. Loading: loads the .class file into the JVM
2. Linking: links the code with the libraries that are imported.

Verification – Bytecode is checked for security and correctness.

Preparation – Memory is allocated for static variables.

Resolution – Symbolic references are replaced with actual memory references.

3. initialization: initializes the class.


Class loader accesses the method area which includes:
1. class metadata
2. static variable
3. constant variable
Method area communicates with
1. Local variables
2. stack

Execution Engine:

It is the heart of the JVM

It consists of three components - Interpretor, compiler and program counter.

it will be connected to the stack

It will include both interpretor and the compiler2

It will communicate with heap for the actual data inside the methods.

Execution engine will use native method interface. (JNI)

It will convert the code to machine level or native level.


Execution engine can also use Native Method Library

1. These are the libraries which are in a different language


2. java supports only 2 languages of native method library which are c and c++

Execution engine executes the code line by line meaning interpreted.

The compiler is used when a code is frequently used

Type Conversion:

Java supports two types of type conversion:

1. Implicit
2. Explicit

Implicit(Widening):

This is done automatically by the compiler.


Converts a smaller data type to a larger data type.
No data loss.
Follow type compatibility.
byte$\rightarrow$short$\rightarrow$ int$\rightarrow$long$\rightarrow$float$\rightarrow$
double

Example:

int a = 10;
double b = a;
[Link](b);

output:
10.0

Explicit(Type Casting):

Done manually by the programmer.


Converts a larger data into a smaller data type.
Possible data loss.
Requires casting operator.

Example:

double d = 2313123.21;
int i = (int)d;

Control flow statements:

used to control the flow of the program


There are three types of flow statements:
1. Conditional/Decision-Making statement: Used to check some condition before executing the
code.
1. if
2. else
3. if else
4. switch
2. Repetition statement
3. Jumping statements

Code for conditional statements:

import [Link];
class hasVoterId{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
if (age>=18) {
[Link]("Eligible for voting");
}
else{
[Link]("Not eligible");
}
[Link]();
}
}

Here curly braces after an if statement is options IF THERE IS ONLY ONE LINE OF CODE

Nested if else blocks:

class nestedIfElse {
public static void main(String[] args) {
boolean hasMoney = true;
int money = 300;

if (hasMoney) {
if(money>=300){
[Link]("Can go to the movie");
}
else{
[Link]("Paisa nahi hai");
}
}
}
}

Switch:

Switch statement is used when we want to execute a block of code based on the value of a single
variable

[Link]
Syntax and example for switch:

class Switch {
public static void main(String[] args) {
String day = "Sunday";
switch (day) {
case "Monday":
[Link]("Today is monday");
break;

case "Tuesday":
[Link]("Today is Tuesday");
break;
case "Wednesday":
[Link]("Today is wednesday");
break;
default:
[Link]("Enter a valid day");
} } }

Arrays in java:

In java we can create arrays using:


int arr[] = {1,2,3,4}
int arr[] = new int[<size>]

2d arrays:

To define 2d arrays:
we use the syntax : int arr [] [] = {{1,2,3,4,5},{6,7,8,9,10}}
Defining an empty 2d array : int arr [] [] = new int[<size-of-rows>][]

[Link]

each row is a separate object in the memory [Link]

Repetition statements:

1. while
2. do while
3. for

While:

Used when we are not aware of the iteration.

class While{
public static void main(String args []){
int i = 0;
while(i<11){
[Link](i);
i++;
}
}
}

Now this loop will run till the condition is true.

DO-while:

the do block will run once at least once after that it will check conditions.

public class doWhile {


public static void main(String[] args) {
int i = 0;
do {
[Link]("This is to test the do while");
i++;
} while (i < 10);
[Link]("testing");
}

For:

Used when numbers of iterations is known


Used to traverse over datasets
There are two types of for loops in java:
1. Standard for loops: for(intialization; condition; updation){}
2. Enhanced for loops: for(datatype <variable name> : data)
manipulation is not applicable.
Generally used for traversing.

Code for For loops

class xyz{
public static void main(string [] args){
int arr[] = {1,2,34,5,5};

for(int i = 0; i<[Link]; i++){


[Link](i + " ");
}
}
}

Code for enhanced for loops:


class xyz{
public static void main(string [] args){
int arr[] = {1,2,34,5,5};

for(int i : arr){
[Link](i + " ");
}
}
}

Iterating over 2-D arrays:

If an array contains equal number or rows and columns then we can simply iterate it using 2 for loops
and using the array length.
For example:

public class twoArray {


public static void main(String[] args) {
int arr[][] = {{1,2,3},{4,5,6}, {7,8,9}};
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < [Link]; j++) {
[Link](arr[i][j] + " ");
}
}
}
}

Here both rows and columns are same so we can iterate it simply using two for loops.
In the case of jagged arrays or arrays where the number of rows and column will not be the same, We
have to use other methods to access:

public class twoDArrays {


public static void main(String[] args) {
int arr [] [] = { {12,3,4},{6,7,8,9,12} };
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arr[i].length; j++) {
[Link](arr[i][j] + " ");
}
}
}
}

Here we are using j < arr[i].length this helps in automatically adjusting the value of the condition
so it does not go out of bounds.
In this example when the value of i will be 0 so the value of arr[i].length will be 3.
When i = 1 then the value of arr[i].length will be 5.

Jumping statements:
There are two jumping statements
1. continue: Used when we have to skip a particular iteration
2. break: Used to completely exit from a block and stop its execution
Example for break and continue:

for(int i = 0; i<11;i++){
if(i==9){
break;
}
if(i==7){
continue;
}
[Link](i + " ");
}

Difference between length and length():

length() finds the number of elements in a data structure

This method is used for strings.


String is a full class

length is used for arrays.

This keyword gives the length of array


it is stored as a property inside the array object.
length is used for arrays because java internally creates an array object
length is a final variable which stores the size of the array.

Wrapper class:

Wrapper classes are used to replace primitive datatypes with objects.


As java is a oop language using data types is not preferred.

Autoboxing and unboxing:

Autoboxing will be used to convert normal data type into wrapper classes.

1. char -> Character


2. int -> Integer
3. float -> Float
4. long -> Long

Rest of them will have their first letter capital

when we have to convert wrapper classes into primitive data types we use unboxing.

Collection framework:

collection of data structures.


We can use this for replacing non primitive
We can import this from the class util class.

Vector:
Stores same datatype
syntax = Vector<String> vc = new Vector<>();

Inheriting from a class:

we use extends to inherit from a class


syntax: class abc extends def{}
has-a relation

Types of Inheritance:

1. single level: single parent and single child class


2. multilevel: Parent class $\rightarrow$ child class $\rightarrow$ child’s child class
3. multiple: java doesn’t support multiple level inheritance
4. Hybrid
5. Hierarchical inheritance: one parent class but multiple child class inheriting from the same parent
class [Link]

Single level:

class Vehicle{
int a = 10;
void engine(){
[Link]("Engine is working");
}
}

class Car extends Vehicle{


void fuelType(){
[Link]("Fuel type is petrol")
}
}

class SingleInheritance{
public static void main(String args[]){
Car o1 = new Car();
[Link](o1.a);
[Link]();
[Link]();
}
}

Multi Level:

class University{
final static String name = "GBU";

void course(){
[Link]("Multiple courses running in the university");
}
}

class School extends University{

void dept(){
[Link]("Multiple schools are running in the department");
}

class Dept extends School{


void CSE(){
[Link]("CSE running multiple computer based courses");
}
}

public class MultiLevel {


public static void main(String[] args) {
[Link]([Link]);
Dept o1 = new Dept();
[Link]();
[Link]();
[Link]();
}
}

Multiple level:

Multiple parent class for a child class


Java doesn’t support multiple level inheritance
Can be done using interface

Hybrid:

combination of more than one type of inheritance

Hierarchy:

only one parent class but multiple number of child are possible

Requirement of inheritance:

1. code re usability

Overriding (Run time polymorphism):

It is the process of re defining a method that is present in the parent class.


class A{
void show(){
[Link]("Parent class");
}
}

class B extends A{

@Override
void show(){
[Link]("Child class");
}
}

public class Overriding {


public static void main(String[] args) {
B o1 = new B();
[Link]();
}
}

Super Keyword:

It is used when we have to call the variables, methods and constructor from the parent class
We can only call the constructor of a parent class but we cannot override it.
Constructors belong to a particular class and hence cannot be overridden

class A{

A(){
[Link]("Constructor of parent class");
}
int x = 20;
void show(){
[Link]("Parent class");
}
}

class B extends A{
B(){
[Link]("Constructor of child class");
}
int x = 30;
@Override
void show(){
[Link]();
[Link]("Child class");
}
void printX(){
[Link]("The value of x is: " + super.x);
}
}

public class SuperConstructor {


public static void main(String[] args) {
B o1 = new B();
[Link]();
[Link]();
}
}

super() is used to call the constructor of parent class


even if we don’t use the super keyword, Java still calls the constructor of parent class while creating
the object

Inhibiting Inheritance:

To stop a child class from inheriting the parent class we can use the final keyword.
final keyword stops the parent class from getting inherited

final class A{

A(){
[Link]("Constructor of parent class");
}
int x = 20;
void show(){
[Link]("Parent class");
}
}

class B extends A{
B(){
[Link]("Constructor of child class");
}
int x = 30;
@Override
void show(){
[Link]();
[Link]("Child class");
}
void printX(){
[Link]("The value of x is: " + super.x);
}
}

public class InhibitingInheritance {


public static void main(String[] args) {
B o1 = new B();
[Link]();
[Link]();

}
}

[Link]: error: cannot inherit from final A


class B extends A{
^
1 error
error: compilation failed

Dynamic Method Dispatch:

It is the process where a method is decided at runtime based on the object’s actual type. Rather than
reference type
Dispatcher is used to connect the request
output depends on the constructor which is being used while creating the object

class A{

// A(){
// [Link]("Constructor of parent class");
// }
int x = 20;
void show(){
[Link]("Parent class");
}
}

class B extends A{
// B(){
// [Link]("Constructor of child class");
// }
int x = 30;
@Override
void show(){
// [Link]();
[Link]("Child class");
}
void printX(){
[Link]("The value of x is: " + super.x);
}
}

public class DynamicMethodDispatch {


public static void main(String[] args) {
A o1 = new B();
[Link]();
}
}

Modifiers:

A modifiers is the statement which controls the accessibility, behavior and properties
They are of two types:

1. Access modifier: Used to control accessibility of the class, variable and methods

public: can be accessed from the same class, subclass and can be accessed in same
package can be accessed in different package
protected can be accessed from the same class, subclass, can be accessed in same
package but not in different package
private: can be accessed from the same class. Cannot be accessed in subclass and
same package and different package
default: can be accessed from the same class, subclass and cannot be accessed in same
package and different package

2. Non-access modifier: Used to decide the behavior or control the properties of class, variable
and method

static: used for making the access from object level to class level

final: used for fixing a value of a variable.

If we use final with a class then no other can inherit that class
if we use final in a method within a class then no other class inheriting it will be
able to override it
blank final variable: A final variable that is not initialized at the time of declaration is
known as blank final variable. It can be initialized only in constructor
static blank final variable: A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can only be initialized in static
block

abstracted: both class and method can be abstract.

In class: an abstract class can contain both abstract and non abstracted methods
In method: methods which are incomplete are by default abstract. Abstract method
will only be used in abstract class
For ex: public void func();
This is an incomplete method

abstract class xyz{


pubilc void xy();
}
class xy extends xyz{
public void xy(){
[Link]("Hello");
}
}

Abstraction:

To achieve abstraction we can use abstracted class or interface

Abstracted Class:

with abstracted class we can only achieve abstraction partially


need to create final or static variable, they are optional
method may be abstract or may be concrete
To create abstract class or abstract method we need to use abstract keyword
Object cannot be created of abstracted class
Abstract class can only be used after inheriting
The inheriting class must implement all the abstract methods that are present in abstract class

abstract class EmployeeRecords{


void Info(){
String Companyname = "Abc";
[Link]("The name of the company is: %s", Companyname);
}

abstract void Salary(); // abstracted method without body


}
class EmpSalary extends EmployeeRecords{

void Salary(){
int sal = 50000;
[Link]("Salary is: " + sal);
}

public class Abstraction{


public static void main(String[] args) {
EmpSalary o1 = new EmpSalary();
[Link]();
[Link]();
}
}

Interface:

An interface is a blueprint of a class which holds only final variable and abstract method

with interface we can only achieve abstraction completely

can contain final and static variable by default without using any keyword
only abstract method are allowed by default without any keyword
use interface keyword to create interface or abstract method created without any keyword
Object cannot be created of interface
Interface can only be used after implementing
concrete methods can be created using the default keyword

Packages:

Random numbers:

import [Link];
class RandomNumbers{
public static void main(String[] args) {
Random rn = new Random();
int num = [Link](100); // this is the range 0-100
[Link]("Random Numbers: " + " " + num);
}
}

String:
Collection of characters, enclosed in double quotes
String is a class that belongs to lang package
lang package is imported automatically
String s1 = "Anuj";

class Strings {
public static void main(String[] args) {
String s1 = "Hello "; // address of memory 231324
[Link](s1);
String s2 = "World";
s1 = "testing"; // address of memory 2323124
[Link](s1);
[Link](s1 + s2);
}

Strings are immutable, each time a new object is created whenever a string is mutated
This is called traditional string

String methods:

1. length()
2. toLowerCase()
3. toUpperCase()
4. trim()
5. SubString()
6. indexof("H")

String buffer and builder:


In java, Stringbuffer and StringBuilder are classes used to create and manipulate mutable strings,
unlike the String which is immutable.

In the case of String once the object is created it cannot be mutated. Any modification on that object
will result in a new object, which increases memory usage

traditional string < string buffer < string builder

String buffer:

A stringbuffer is a mutable sequence of characters which is thread safe(synchronized), allowing


multiple threads to safely modify the same String

slow compared to string builder due to being thread safe

String builder:

A stringbuilder is a mutable sequence of characters which is not thread safe

Stringbuilder is faster and suitable for single threaded operations

Stringbuilder is faster due to there being no locking overhead since its not thread safe

StringBuffer and StringBuilder methods:

Both share almost the same methods:

1. append(): adds text to the end


2. insert(): insert texts at a specific index
3. Replace(): replaces character between indexes
4. delete(): deletes character between indexes
5. reverse(): reverses the string
6. capacity(): Returns the current capacity. Default is 16
when capacity is full and has to be increased java does it by
new capacity = (old capacity *2 ) + 2
7. ensureCapacity(): increases the capacity if needed
8. charAt(): returns the character at a index
9. setCharAt(): changes the character at a index
10. length(): returns the length of the string

Multithreading:
Multithreading is a java feature that allows a program to execute multiple threads concurrently with a
single process. It is used to improve the performance, responsiveness and efficient utilization of the
CPU resources

Thread is the smallest unit of execution in a program. Each thread runs independently but shares the
same memory space of the process

Advantages of Multithreading:

1. Improves program performance


2. Enables concurrent execution
3. Better CPU utilization
4. Enhances responsiveness of application
5. Suitable for real time and interactive systems

Applications:
1. Web servers
2. Gaming applications
3. Multimedia processing
4. Real-time Systems

Creating a thread:

Method1: Extending Thread class

In this method we extend the Thread class and overrides the run() method.

class MyThread extends Thread{


public void run(){
[Link]("Thread is running")
}

public static void main(String args[]){


MyThread t = new MyThread();
[Link]();
}}

The run() method contain the code executed by the thread


the start()method cretes a new thread and calls run() internally
Directly calling run()will not create a new thread

Method2: Implementing Runnable interface(preferred way):

class MyRunnable implements Runnable{


public void run(){
[Link]("Thread using runnable")
}

public static void main(String args[]){


Thread t = new Thread(new MyRunnable());
[Link]();
}}

Thread lifecycle:

1. new state: Thread is created but not executing


2. running state: The code is executing.
3. Block state: Thread can be blocked or can enter waiting state,
Waiting state while waiting for IO resources
Block state while the thread is sleeping
4. Timed waiting state: A thread is stopped for some amount time using sleep method
5. Terminated : Execution is completed and the thread is terminated.

// Blocking Thread Example


class MyThread extends Thread {
public void run() {
for(int i = 1; i <= 5; i++) {
[Link]("Running: " + i);
try {
[Link](1000); // Thread blocked for 1 second
} catch(Exception e) {
[Link](e);
}
}
}
}
public class Test {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();
}
}

Stopping a thread:

class MyThread extends Thread {


boolean running = true;

public void run() {


while(running) {
[Link]("Thread is running...");
try {
[Link](1000);
} catch(Exception e) {}
}
[Link]("Thread stopped.");
}
}

class Test {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();

try {
[Link](3000); // Main thread waits 3 sec
} catch(Exception e) {}

[Link] = false; // Stop thread safely


}
}
Thread methods:

1. [Link](): calls the run method as a new thread


2. [Link](): contains all the code inside the thread. Directly calling run() wont create a new thread
3. [Link](<milliseconds>): blocking the thread for given time.
4. [Link]():
5. [Link](): Gives other thread a chance to run
6. [Link](): sets the name of the thread
7. [Link](): returns the name of the thread
8. [Link](): gives the priority to the thread value is between 1 - 10
9. [Link](): returns the priority of a thread
10. [Link](): returns true if the thread is running.
11. [Link](): running thread can be interrupted
12. [Link](): Deprecated in java. Logic is used instead

Thread Exception:

class MyThread extends Thread {


public void run() {
try {
[Link]("Thread sleeping...");
[Link](5000);
} catch (InterruptedException e) {
[Link]("Thread interrupted!");
}
}
}

public class Test {


public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();

try {
[Link](1000);
} catch (Exception e) {}

[Link](); // Interrupting thread


}
}

JDBC:
It stands for java database connectivity.
It is an api in java that allows your program to connect to a database.
It is the part of java standard edition
Java standard edition
java enterprise edition: For web apps

Features of JDBC:

1. Platform independent
2. Supports multiple database
3. Provides standard interface for the database access

Drivers

The component that actually enable communication between your java program and a specific
database
A JDBC driver is a software module that implements the JDBC API and allows java application to
connect to a database
JDBC uses 4 types of drivers:
1. Type-1 Bridge
2. Type-2 Native
3. Network
4. Thin

Type-1 Bridge:

1. Uses ODBC to connect java applications to the database


Working:
Java $\rightarrow$ JDBC API $\rightarrow$ JDBC-ODBC Bridge $\rightarrow$ ODBC
Driver $\rightarrow$ Database
2. Depricated after java8
3. Can be converted to any database !6- Media/Pasted image [Link]

Disadvantage:

1. Performance degrade

Type-2 Driver Native:

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
Returns in C or C++

Type-3 Network protocol driver:

The network protocol driver uses middleware that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is fully written in java - Returns in java

Type-4 Thin Driver:

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it
is known as thin driver. It is fully written in Java language

Architecture:

!Media/Pasted image [Link]

Steps to connect jbdc:

import [Link];
import [Link];
import [Link];
import [Link];
class question120 {

public static void main(String[] args) {

String url = "jdbc:mariadb://[Link]:3306/company";


String user = [Link]("DB_USER");
String password = [Link]("DB_PASS");

try {
[Link]("[Link]");

Connection con = [Link](url, user,


password);

Statement stmt = [Link]();

ResultSet rs = [Link]("SELECT * FROM customers");

while ([Link]()) {
[Link]([Link]("Cid") + " " + [Link]("Cname")
+ " " + [Link]("City"));
}

} catch (Exception e) {
[Link]("Error: " + [Link]());
}

[Link]("Name: Anuj Singh\nRoll number: 245UCM004");}


}

1. this keyword is used to refer to the current object.

it differentiate instance variable with parameter


call another constructor

2. the Just in time compiler is a component of JVM that improves the performance of Java
applications by converting bytecode into native machine code during runtime.↩

You might also like