Reading view

There are new articles available, click to refresh the page.

spring Boot Introduction -II

Step:1 Open Eclipse
If you Don not install ,install
https://www.eclipse.org/downloads/

Step:2 Install Spring Tools (Spring Tool Suite 4) Plugin
1.Go to menu:
Help-> Eclipse marketplace
2.Type Spring tool In search bar
Spring Tools 4 (aka Spring Tool Suite 4)
then install. Restart Eclipse.

Step:3 create spring boot project
File->New-> Spring starter Project.

Demo1 obj1 = new Demo(); // tightly couple
Demo1 obj1; // loosely couple

Now not need any dependencies , now I skip dependencies.

Image description

Jar,War,Dependencies,Pom.xml,Maven,Gradel,Spring,Spring Boot,yml,Application properties,Tomcat..etc to read this Blog:
https://dev.to/prasanth362k/spring-boot-1-2-class-14h0

Group:Package name
Artifact: Project Name

Image description

Project Structure:-

Image description

Demo1 is project name

src/main/java:

This folder contains your java source code:

  • @SpringBootApplication main class
  • Controllers (@RestController)
  • Services (@Service)
  • Repositories (@Repository)
  • Model classes (@Entity)

src/main/resources

This folder stores all configuration and static files like:

  • application.properties or application.yml
  • static/ (HTML, CSS, JS)
  • templates/ (Thymeleaf or JSP)
  • .sql or .xml files (if needed)

this location configure Database url,Db username/password,server port number.

src/test/java

This used for writing Junit test cases to check if controller/Api is working?,Service logic is correct?, function returns should give correct output.it helps tester and developer find bugs early.

In real time first we done testing the project then deployment.

JRE System Library [JavaSE-17]

This Library provide all the core java classes (like String,List,System.out.println) you project needs.without library won't understand basic java code

For Example-

System.out.println("Hello World");  // Needs java.lang classes from JRE

why it's need?
java compiler version ( project built in using java 17),Runtime version ( you app will run run on java 17), this both need java 17 or higher version for spring boot .that need to your project.

Image description

Image description

Maven Dependencies

This file contain .jar file(libraries) downloaded form maven(internet) based on you what you add dependency from pom.xml .

why and what Maven dependencies and JRE System Library [JavaSE-17] both contain jar file inside package and inside .class file.

Maven Dependencies:

Image description

JRE System Library [JavaSE-17]:

Image description

.jar -> is a compressed file format or Zip folder for .class file,.jar contain .class, .properties,xml related. it user for java application not for web application(war) , can be executable to run with java -var app.jar(main class) , inside .jar you see .compile files.

.class , created after compiling .java,platform indepenedent(can run any osusing jvm),it is not human readable(byte code(plain text)),it is single file not a zip folder

target/

maven stores all compiled code and build files here.After mvn install, .class and .jar files go here.his is auto-generated – don't modify manually.

pom.xml

The main configuration file for Maven:
Add dependencies (Spring Web, JPA, Lombok)

In this blog i demonstrate how to call method without object new keyword only class reference not create object like.Before 2 thing definitely to know one for what is tightly coupling and loose coupling why to use then what is spring container please read my previews blog

By Default Main program start this file

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.example.demo.service.SMSNotificationService;



@SpringBootApplication
public class DemoApplication {

    private NotificationService notificationService;

    public static void main(String[] args) {
        // before SpringApplication.run(DemoApplication.class, args);
        ConfigurableApplicationContext context  = SpringApplication.run(DemoApplication.class, args);// after 
        //it is tigtely couple relation to avoid like without new key word
        SMSNotificationService sms =context.getBean(SMSNotificationService.class);
        //SMSNotificationService sms ; // = new  SMSNotificationService();
        //SMSNotificationService sms;
        sms.send_message("abcd ","1234");
    }

}

Step:2
I created SMSNotificationService class

package com.example.demo.service;


import org.springframework.stereotype.Component;

import com.example.demo.NotificationService;

@Component
public class SMSNotificationService implements NotificationService{

    @Override
    public void send_message(String to ,String message)
    {
        System.out.println("Sending SMS "+to +" : "+message);

    }
}


Step:3 created Interface

package com.example.demo;

public interface NotificationService {

    //abstract method 
    void send_message(String to ,String message);

}

Program Explanation:

SpringApplication is a Built in spring boot class ,it is helps to create environment for your project .
it does 3 thing: start your spring boot application , create the spring container when run this method SpringApplication.run(DemoApplication.class, args), DemoApplication.class, args why to use you are tell to the spring boot where to begin otherwise spring boot do not know where to start you said start from main.then why args , to pass to arguments in command line like: java -jar app.jar --server.port=9090
,args will contain --server.port=9090, so spring boot can read setting from command line. that all , then i already told SpringApplication.run(DemoApplication.class, args); it give Spring container just like environment(சூழல்)(to create object inside the environment), we create environment like spring container where will be stored that place is ConfigurableApplicationContext (in Built interface)context (reference variable)

SMSNotificationService sms = context.getBean(SMSNotificationService.class);

we Already marked SMSNotificationService @Component annotation ,which tell spring please create object of this class and manages,SpringApplication.run(....) when run this method , start this app and return ConfigurableApplicationContext, this is the spring Container(environment) that manage the all object(beans) ,we already know that ,already created object , now just get the bean(object) of class SMSNotificationService.class from spring container ,then store the variable sms , then call method sms.send_message("abcd ","1234");

context is a reference to the Spring container,getBean(inbuild function)

**
Inversion of control(IoC) and Spring Container and Dependency Injection(DI) lets connect with together?**

  • IoC is a design principle/idea that says:
  • you should not create objects manually using new,instead spring will manage them ,Spring fallow the principle using technique is called DI.Spring container is the environment the create ,store, and manages all thes beans(objects),these object created and stored heap memory,DI achived using Constructor Injection ,Field Injection,Setter Injection.To inject dependencies spring use the @Autowired annotation
    .

  • If you Do not mention @componet on top of class , spring can not create and store object in the spring container.

  • @Component creates one object inside Spring container (by default singleton). by default singleton mean, by default, Spring creates only one object per class → this is called singleton scope.

  • spring by default create only one object per class , can we create multiple? yes

We learned 2 annotation in this blog:-

@springBootApplicaion
point your mouse arrow int this annotation the press f3 you will some info.
Inside you see lot of annotations combines , in this annotation 3 is important:

1.@Configuration: spring tells this class provide object(bean) , spring should register them spring container.@bean tells spring please call method,take return value and store it spring container.(Do not need to call method manually , automatically call)

Example:-

@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}

2.@EnableAutoConfiguration

Tells Spring boot will automatically configure beans based on what is in the classpath For example , you add spring web in pom.xml configure Tomcat server , web settings(DispatcherServlet ), set port automatically you do not do manually ,this automatically configure.
"DispatcherServlet is the front controller in Spring MVC.
It handles all incoming web requests and routes them to the correct @Controller or @RestController methods."

  1. @ComponentScan

Spring scan the current package and sub package @Component,@Service,@Controller,
@Repository automatically create objects(beans) and store them container.Before i said if you mention top of the class @Component object created and store in spring container , @Service,@Controller,
@Repository internally @Component you can point you mouse cursor in annotation and press f3 .
it will create objects only for classes :

  • @Component
  • @Service
  • @Controller
  • @Repository

mvt vs mvc

spring & Spring Boot

What is framework?

  • A framework is like ready made toolset or structure ,it helps you build application easily , without starting from scratch.

what is spring?

  • Spring Framework is a java-based opens-source framework , it is used to build enterprise level, scalable, maintainable application.
  • spring provide infrastructure support for building java apps by managing dependencies injection , configuration, connecting to databases, handle web request and so on.
  • Need External Server (Tomcat)
  • Developed by Rod Johnson in 2002.

  • Spring Follows principle Dependency injection(like without new keyword create the object, spring container(object memory location) ,to use @Autowired) and Aspect-Oriented programming(AOP),MVC(Model-view-Controller)

  • AOP: is a programming concept to used to separate common function like logging ,security,transactions from main logic of you application. simple, write common code(logging, security, transactions) and automatically apply you app or application , without rewrite it everywhere

  • Deployment : Build WAR, needs external server

  • Configuration: Manual xml based configuration it is older style ,you define everything in xmf flie.spring 2.5 version you can use also annotation so spring support both XML and annotation , but need more setup. in Spring boot no need xml Configuration you just add dependencies in pom.xml,it will auto configure everything ,start the application , scan your classes with annotation like @Restcontroller ,@Service ..etc.

spring Example:-

applicationContext.xml or beans.xml

<bean id="studentService" class="com.example.StudentService"/>
<context:component-scan base-package="com.example"/>


spring boot dependency injection Example:-

pom.xml 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>


before you added dependency in pom.xml ,now Spring boot code now you can use annotations @ annotation:-

@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello!";
    }
}

<bean id="myBean" class="com.example.MyBean"/>

Annotation-based:-
you use java annotation instead of xml
Common annotations:

@Component, @Service, @Repository, @Controller ...etc

What is annotation:-

Annotation is meta data that mean data about data, data about data mean provide info about to the spring framework,These annotation used to configure,customize, reduce xmL configuration and boilerplate code ( repeated code not a main logic), annotation make developer develop application or app simplify development and maintain and efficient ,time reduce..etc.

How to avoid boilerplate code:-

  1. manual creating beans:-
<bean id="studentService" class="com.example.StudentService"/>

how to avoid : use annotation like @service and @ auto wired ,automatically crate and inject bean(object).

  1. Auto Configuration Automatically set up Db ,server..etc.it make consuming more time and managnet difficulty so, how to avoid:
  • spring boot add automatically configure you application based on dependencies what you added in the pom.xml and some more setting in application.properties or application.yml. like you want project server tomcat , you can inject dependencies your pom.xml(maven) spring automatically download internet you dependencies.

  • In a project you can see src/main/properties under you can see application.properties it used to .

  • Configure application setting like port number changing ,Db config..etc.

3.Getter/setters
How to avoid Getter/setters : Lombok , remove getter/setters , use @data and @Getter ,.etc.

application.yml:-
YAML format for settings

What is Dependencies and Dependencies injection and types:-

Dependency:-
Dependency is a class/object that another need to work.
Example:-

class Engine
{
public void start()
{
sytem.out.println("engine started Let to drive");
}
}
class Car {
    Engine engine = new Engine();  // tightly coup
    engine.start();
 // Engine is a dependency
// Engine class change constructor , you must chage  every place that  uses it.  
}

// car depends on Engine , so Engine dependency of car

What is Dependency Injection (DI)?

  • Dependency Injection is a is a design pattern, do not create the object yourself with new key word(tightly couple) ,spring or spring boot create and inject required object with help of @Component(you can tell spring ,pleas create objects of this class,spring will manage and create bean(object) ),spring container(memory location hold all object (@Componet in top of class use )),@Autowired (connector like tell spring inject(connect) this object here) ,spring container is one of the part of heap memory. Why Heap? Because:
  • All Java objects are stored in the heap memory
  • Spring beans are also Java objects.

Example:

Normal java or spring boot or spring you can create object with new keyword it is manual ,it make depend upon other like called tightly coupled when depender class anything change(parent)like constructor like parameter constructor/overload ,you can change all so depending class(child class) constructor or object values.



class Engine
{
public void start()
{
sytem.out.println("engine started Let to drive");
}
}
class Car {
//Engine engine = new Engine(); // Manual
@Autowired
Engine engine; // Spring injects it

    engine.start();
 // Engine is a dependency
// @Autowired if you want you first  inject dependency  to pom.xml , maven will manage

}

Why to use DI:-

  • Reduce manual object creation
  • Loose Coupling - easy to change

Types of Dependency Injection in Spring?

1. Constructor Injection

Spring passes dependency to the constructor

@Component
class Car {
    private final Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }
}


2️2.Setter Injection:-

Spring sets dependency using setter method

@Component
class Car {
    private Engine engine;

    @Autowired
    public void setEngine(Engine engine) {
        this.engine = engine;
    }
}


3. Field Injection

Spring injects directly into the field

@Component
class Car {
    @Autowired
    private Engine engine;
}

Aop example:

without AOP( repeating code every where)

public class BankService {

    public void withdraw() {
        System.out.println("Checking permission...");
        System.out.println("Logging: withdraw started");
        System.out.println("Withdrawing money...");
        System.out.println("Logging: withdraw completed");
    }

    public void deposit() {
        System.out.println("Checking permission...");
        System.out.println("Logging: deposit started");
        System.out.println("Depositing money...");
        System.out.println("Logging: deposit completed");


    }

    public void checkBalance() {
        System.out.println("Checking permission...");
        System.out.println("Logging: check balance started");
        System.out.println("Showing balance...");
        System.out.println("Logging: check balance completed");
    }
}

// main logic with extra logic , hard to mange,messy..etc

With AOP (clean and separate)

public class BankService {

    public void withdraw() {
        System.out.println("Withdrawing money...");
    }

    public void deposit() {
        System.out.println("Depositing money...");
    }

    public void checkBalance() {
        System.out.println("Showing balance...");
    }
}
Step 2: Write AOP for Logging and Permission
@Aspect
@Component
public class LoggingAspect {

    // Log before any method in BankService
    @Before("execution(* com.example.BankService.*(..))")
    public void logBefore(JoinPoint jp) {
        System.out.println("Logging: " + jp.getSignature().getName() + " started");
    }

    @After("execution(* com.example.BankService.*(..))")
    public void logAfter(JoinPoint jp) {
        System.out.println("Logging: " + jp.getSignature().getName() + " completed");
    }

    @Before("execution(* com.example.BankService.*(..))")
    public void checkPermission() {
        System.out.println("Checking permission...");
    }
}
// But you didn’t write this logging or permission code inside the withdraw() method — Spring AOP handled it for you.

Is Spring only for Java?

yes, Spring is only for Java and JVM-based languages (like Kotlin, Groovy).
It is not for Python, C++, etc.

Why use Spring?

  • To build robust(Strong,stable,handle errors well,)loosely coupled(classes are independent not tightly coupled , Java applications. Can integrate with JPA/Hibernate, JDBC, Security, etc.

JPA (Java Persistence API)

  • JPA is just a specification (like a set of rules).
  • It defines how Java objects should be saved into a database (ORM – Object Relational Mapping).
  • JPA doesn’t do anything by itself – it needs a real tool to work.

Hibernate

  • Hibernate is a real tool (framework) that follows JPA rules.
  • So, Hibernate is a popular implementation of JPA.
  • It does the actual work of connecting your Java classes to the database. Example:-

Think of:-

JPA = Rulebook

Hibernate = Worker who follows the rulebook

  • sql maually, JDBC, Security, etc.

What is JDBC?

  • JDBC = Java Database Connectivity (manual SQL writing and executing)
    

    When to use:

  • When you want manual control over SQL.
    

    How Spring Integrates:

  • Spring provides Jdbc Template to reduce boilerplate code.

Spring Security:-
What is it?

  • A module in Spring for:
  • Login/Logout
  • User Roles (admin, user, etc.)
  • Password Encryption
  • Authorization (what a user can access)

How Spring Integrates:

  • Add spring-boot-starter-security
  • Configure user roles, login form, URL access rules Example

Tightly coupling:-

class Car {
    Engine engine = new Engine(); // direct object
}

loose coupling

class Car {
    @Autowired
    Engine engine; // Spring will inject it
// you can change the engine ,test the calss , or reuse iit 
}

  • IT save time ,Make code clean and reusable
  • It give tools for web apps ,security ,database,JPA/Hibernate, JDBC.
  • Supports DI, AOP, and MVC, simplifying development.

what is Spring Boot?

  • Spring boot is a simplified version of the Spring Framework. It helps to create spring applications quickly and with less configuration.

  • Spring Boot = spring + Ready made setup(like auto configuration ..etc) +Less code + fast to development like you can create java web apps to fast.

  • Developed by Pivotal (now VMware) in 2014.

  • Deployment : Build JAR with embedded Tomcat/Jetty(server)

Use Case:-

spring : Full control, more configuration setup ,suitable for custom projects
Spring Boot: Fast startup the projects,Rest APIS, Micro-service, ..etc.

Example:

  • without spring: you write 100 lines for setup code.
  • with spring : you write 20 lines.
  • With spring Boot : you write 10 lines

why to use Spring Boot?

  • Reduce boilerplate code( boilerplate code- repeated code , you write agin and again) ,to avoid writing unnecessary code.
  • Easy to start project with pre-configured setups.it useful for beginners.
  • To avoid complex XML configurations.
  • Ideal for micro services architecture

*we will learn some concept or tool or other terminology used in the spring boot project *

What is Maven?

(A Java tool to manage dependencies and build project)

  • Maven is a build and dependency management tool for Java projects.
  • Configuration format : XML (pom.xml)
  • Speed: Slower
  • Used in Spring Boot, standard Java app s
  • Dependency Management: Downloads libraries (JAR files) only from Maven Central repository

- It helps:

  • Download and manage external libraries (like Spring Boot..etc)
  • Build your project (compile, test, package into .jar or .war)
  • Run your project with the required libraries

What is Gradle?

  • Gradle Build & Dependency Management Tool like maven.
  • Configuration format : Groovy or Kotlin DSL (build.gradle)
  • synax: Concise like script based
  • speed: Faster
  • Dependency Management: Can download from Maven Central, JCenter, or custom/private sources.
  • used in : Andriod apps, spring Boot Apps ,large java projects.

What is jar ?

jar = Java ARchive

  • Jar File is a packaged java application(all java files are combined into one file .jar so it easy to run ,share,or deploy ) used to run standalone programs.JAR file is a zip file that contains your Java program

standalone mean:

  • work independently.
  • no need to deploy on separate server tomcat manually.that mean just run the jar file directly using java no need to put in separate server like tomcat.
  • Easy to run,test and move.

Example:

  1. you build you spring boot app like myapp.jar
  2. run using java -jar myapp.jar 3.spring start its own server on port of 8080 by default 4.you open browser ->http://localhost:8080 app is running this is called deployment for JAR
  • Jar file contains all compiled .class files, libraries, and metadata(info about how to run).

  • Runs directly using: java -jar app.jar

  • used in Spring Boot, microservices, and CLI apps.Running desktop or back end apps.Standalone Java applications

  • jar not need install server separately , include tomcat server run app directly
    Tools -> Maven/Gradle to build .jar

what is WAR?

WAR = Web Application Archive

  • A WAR file is a packaged Java web application(means java web project with contain HtmL,CSS,Java code,etc) that zipped into one .war file to be run on a webserver) used to deploy on web servers like Tomcat in deploy. Deploy mean putting your application on a sever so users can access it.

  • WAR Contains: .class files + HTML, CSS, JS, JSP, WEB-INF folder, etc.

Example:-

1.you build you app -> myapp.war ( create you web app)

2.you copy to C:\tomcat\webapps\myapp.war (after placed your web app in the server tomcat)
3.Start tomcat
4.open browser and paste => http://localhost:8080/myapp (server run your app and it make available in the browser)
now deployed and running

Deploy -> Putting your app on a server to run
WAR file -> The package you give to the server
Tomcat -> The server that runs your web app.

  • used for Deploying java apps to web server(Apache Tomcat) .Web-based applications (Servlet, JSP, deployed to server)

  • Tools -> Maven/Gradle to build .war

What is pom.xml in Spring Boot ?

(XML file used by Maven to define project setup)
POM = Project Object Model

  • pom.xml it is a XML file(your required dependency placed or add into pom.xml) used by maven tool ,that to tool manage the dependencies in you project. pom.xml tells maven what is project name(artifactId),package name (groupId),what version,What dependencies (JARs) to download,What plugins or settings to use.

What is XML in pom.xml?

XML = Extensible Markup Language
It is used to store structured data.
it use tags likevalue
XML is platform-independent and readable by humans and machines. that mean do not depend on any operating system ,can be used or support on every platform like Windows, linux,mac,android,server...etc

What is a Dependency in pom.xml?

  • I want to use some external java library or tool like spring boot ,jpa,hibernate, please download and include my project. like simply say maven is a tool it mange dependencies in the project,that dependencies placed in pom.xml for example you add dependencies in pom.xml spring tell maven tool download dependencies form internet file like jar file , that jar file combination package and class available.

Example:-

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
// this dependency say  i want to use spring boot for build web application, maven download required library the you add project  @RestController, @GetMapping, etc.

What Happens When You Use Maven?

When you run:
mvn clean install

Maven will:

  1. Read pom.xml
  2. Download all dependencies (JAR files) from the internet (Maven Central)
  3. Compile the code
  4. Run tests
  5. Create a .jar or .war file to run your app

Where Are the JAR Files Stored?

Maven downloads all .jar files into:

C:\Users\YourName\.m2\repository   (Windows)
or
~/.m2/repository                   (Linux/macOS)
  • JAR in Maven Downloaded from the internet and stored in .m2

java is WORA feature write once anywhere ,platform independence , windows, linux.
500 .class to files to :Zip : in java caller jar

.yaml/.yml

YAML Ain’t Markup Language:Easy to read and write.

  • Used in : Configuration files (application.yml)in Spring Boot, Docker (docker-compose.yml), Kubernetes (deployment.yml), Ansible, etc.
  • Feature : Human-readable data serialization language , indentation-based.

  • Structure: Based on indentation (like Python)

  • Supports: Key-value pairs, lists, nested structures.

  • No tags, no brackets

  • Real-time use: Configure properties like ports, DB, paths.

data serialization language mean:
IT means it help store data in structured ,readable format.
IT can represent data like string,number,list,object..etc.
That data can be converted programming object/variable into a file format like YAML,JSON,XML,binary file so it can be stored or send.

Example:-

Your Java Serialization Code:

import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import java.io.File;

public class SimpleSerialize {
    public static void main(String[] args) throws Exception {
        User user = new User();
        user.name = "Prasanth";
        user.age = 24;

        YAMLMapper mapper = new YAMLMapper();
        mapper.writeValue(new File("user.yml"), user); // Serialization
    }
}

Output in user.yml (YAML format):

name: "Prasanth"
age: 25

reverse code YAML yo JAVA object = deserilation

What is Deserialization?

  • Mean stored convert data format like YAML or JSON or XML(human readable format) back into java/python object or variable.

Example of YAML configuration:

server:
  port: 8080
spring:
  application:
    name: MySpringBootApp
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: user
    password: password
logging:
  level:
    org.springframework: INFO
    com.example.myapp: DEBUG
  • YAML is a language to store and share data in a clean and readable format,used for configuration.

JSON
JSON-JavaScript Object Notation

  • A lightweight, human-readable data format
  • Commonly used for data exchange between client & server. for example spring Boot can automatically convert java object to Json responsce)(Serialization) and JSON to Java object(post)request input (Deserialization) using a library called Jackson by default.
  1. Spring Boot uses Jackson
  • Spring Boot has built-in support for JSON vice versa the Jackson library.
  • Converts (serializes) Java objects → JSON
  • Converts (deserializes) JSON → Java objects
    
  • Happens automatically using annotations like @RequestBody and @ResponseBody (or @RestController)

  • Key Annotations

Annotation Purpose
@RequestBody JSON → Java object (deserialization)
@ResponseBody Java object → JSON (serialization)
@RestController Combines @Controller + @ResponseBody

  • Jackson default Json Processor it is auto configured.

Q1. How does Spring Boot handle JSON?

Using Jackson library (automatically)
Q2. How do you send/receive JSON in REST API? @RequestBody, @ResponseBody, or @RestController
Q3. How do you customize JSON fields? Use @JsonProperty, @JsonIgnore, etc.
Q4. What if the JSON format is wrong?

Spring throws HttpMessageNotReadableException

Important Points

  • Jackson is auto-configured in Spring Boot → no setup needed.
  • JSON input should match Java class field names (case-sensitive).
  • Use validation annotations like @NotNull, @Size with @valid.
  • You can control JSON output with @JsonInclude, @JsonIgnore, etc.
    
  • Real-time use REST APIs, mobile/web apps
    (frontend-backend data exchange)

Tomcat:-
Tomcat is server that run you java web application(WAR) also embedded(include) inside spring Boot Jar apps not java application((JAR)not need install server manually).

  • Spring helps developer connect their web application to number data base.
  • It support relational databases and non relational database
  1. What is a Relational Database (RDBMS)?

RDBS is a Structured data - it mean Data
mean:

  • Data is Stored fixed format in tables(Column and rows) like Excel sheet.Every row must follow the same pattern. like Columns define the pattern(schema) so row must follow it and fill same columns with valid data. or you can not skip columns unless NULL is allowed or it has default value.Note you can not suddenly add 4 the value in the table ,that why structured .
  • Uses Sql (structure Query language) to query and manage data Example:-
CREATE TABLE student (
  id INT,
  name VARCHAR(50),
  age INT DEFAULT 18
);

INSERT INTO student (id, name) VALUES (1, 'Prasanth');

if you try this ,it will fail
INSERT INTO students (id, name) VALUES (2, 'Rahul');

// because RDBMS is Structured data must fallow this rules(column(schema(rule)))the rows.

Image description

above the table:

  • Every row must have 3 values: id, name, and age
  • You can’t suddenly add a 4th value in one row
  • You can’t skip columns unless NULL is allowed. This is called structured data.

Examples of RDBMS:

  • MySQL
  • PostgreSQL
  • Oracle
  • SQL Server

Real-World Use:

  • Banking systems
  • Employee or customer records
  • E-commerce product databases

What is a Non-Relational Database (NoSQL)?

  • Stores data in a flexible format — not in rows and columns.
    No fixed schema — you don’t need to define table structure first.

  • Good for handling unstructured or changing data

Stores data as:

  • JSON-like documents (MongoDB)
  • Key-value pairs (Redis)
  • Graphs (Neo4j)
  • Wide-columns (Cassandra)

Currently using Tools and version:-
Eclipse IDE - 2025-06
Java - Java 21 (LTS)
Springboot -3.5.3
Firefox -v140.0.2
Ubuntu -Ubuntu 22.04 LTS
Tomcat 10.1.42
Database -PostgreSQL 15+

How to add Third party jar add in you project ?

your project right click ,choose bulid path configure build path libraries class-path add-external Jar

How to inject dependency in pom.xml different way ?
https://mvnrepository.com/ you can search your required dependencies(version) paste you in pom.xml.
(Or)
install spring tool for Eclipse https://spring.io/tools( we will see later how to install and use)
(Or)
In Eclipse ->Help-> market place -> search spring latest version.

apachi poi => https://poi.apache.org/

  • Apachi poi is a Java library used to read, write, and modify data microsft office files and generate reports ,Automatic document like:

  • Excel (XLS/XLSX)

  • Word (DOC/DOCX)

  • PowerPoint (PPT/PPTX)

if you want your project you can add this dependencies based on project purpose or need.

Spring boot other some important point:

Spring boot
opinionated view of the Spring platform and third-party libraries so you can get started with minum fuses:- That mean

Spring Boot is opinionated framework , spring boot give default setup like (server(Tomcat),db,JSON..etc) setting,libraries,configurations..etc you can start with basic setup,so you don’t have to decide everything yourself create application faster with less configuration, best for beginners ,if you want decide everything yourself go to spring.

Features

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated 'starter' dependencies to simplify your build configuration
  • Automatically configure Spring and 3rd party libraries whenever possible
  • Provide production-ready features such as metrics, health checks, and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration

Image description

Finally we came conclusion part of this spring boot blog we will upcoming blog
spring boot projects to Travel...

W

How to change spring boot banner and set to the spring profile

How to change spring boot banner in Eclipse IDE?

Step 1: Open your spring Boot Project in Eclipse
Step 2: Open src/main/resources Folder in eclipse

  • In the project Explorer (left side)

expand:

Image description

step 3: Right click resource folder -> New -> file -> Give name LOWER Case Letter only.

Example: banner.txt
then click Finish.

like

src/main/resources/banner.txt

step 4: Add custom banner content

open your created file paste your custom test or ASCLL art.

Example:-

Image description

IF you want your own ASCLL text:

https://patorjk.com/software/taag

Step 5: Right click main class(@SpringBootApplication)

Runs As -> Java Application

IF you Do not Want Banner:-

Step 1: Open application.properties in your project.

Location src/main/resource in Double click application.properties add below line.

spring.main.banner-mode=off

What is a Spring Profile?

In Spring Boot , a profile is a to define different configuration for different environment

For example:

dev (development)
test (testing)
prod (production)

Above mention each profile separate beans(objects) or you configuration setting tells that where you app is running.

Why use Profile?

just think like:

in development ,you want to connect to local database.
int production , you want to connect to live database.

Spring Profile help you switch easily between configuration without changing main code.

How to Set a spring Profile:-

1. create separate Property Files:-

go to:

src/main/resources/

Right click resources folder -> new -> file

create files like:-

application-dev.properties

application-prod.properties

inside file type your configuration details

2. In application.properties

=> application.properties

spring.profiles.active=dev

3.Run the Application :

Right-click main class → Run As → Java Application

weekly notes 24 2025

As summer is here, the days are long. We are going to nearby park in most of the evenings.
Viyan started to play basket ball. I am also learning it along with him.
Got a kids guitar for him. He started to practise it daily.

On Last saturday saturday, Tamil classes concluded for kids, for this academic year. In this month end, we will get 2 months holidays for kids. There will be more outdoor, park, library visits.

TossConf25 ( Tamil Open Source Conference) is happening next month. July 18,19 2025 at St. Joseph’s Institute of Technology, Chennai. Dont miss it if you are in or around chennai.
Interesting talks and workshops are planned. Book your ticket now here – https://TossConf25.kaniyam.com Thanks for the organizing team for the awesome efforts.

I am collecting huge tamil corpus from around 200+ websites daily. Getting content from RSS feeds are easier than scrapping. But need patience to build the huge text content daily. From 200+ websites, getting around 10 MB text content daily. Colelcting the new words and frequently used words, to build the base
of tamil spellchecker.

I am thinking of hosting one more FreshRSS instance with all these RSS news feeds.
We can read adfree news with RSS Feeds.

On exploring the news websites, found the below things

  • Too many advertisements. Signal to Noise ratio is too high. We will lose interesting reading with this high amount of advertisements.
  • Many websites dont provide RSS feeds. The custom platforms they use dont have RSS feed feature.
  • For few of the wordpress websites, the admin disabled RSS feeds.
  • Few site feeds provide only headings on the feeds.
  • Cloudflare prevents feeds to be read by any feed reader, except the browser.
  • Many writers have their websites, but not writing there frequently. But so active on social media.
    They should atleast keep a copy on their websites,blogs.

    Used the below plugin to get the RSS feed link from the websites. – Rsshub Radar – https://chromewebstore.google.com/detail/rsshub-radar/kefjpfngnndepjbopdmoebkipbgkggaa

Sad to see that Google is showing only 7-8 pages of text content websites. After that, for all queries, we are getting only youtube video links. Whatever we write, google will show only form the mainstream websites.

I am reading more about the copyrights and Rss feeds.
Is it fine to get the full text rss feed and open them all to the public for free reading?

It will be super good to read text without any advertisements, banners, popups, and distractions.
But, the copyright is tricky here. Writers will agree to send their content via email for subscribers, via RSS feed for any personal feed readers. But, may not agree for public feed aggregators.

is it okey to give login credentials for users, to read the content?

I will check with few friends and mentors on what they think.
Reply here on what you are thinking on this.

Here is a screenshot of freshrss shows content from various websites.

Work is going super busy with many new activities. Lot of new learnings on AWS and networking.

Published a video by Nithya on “Basics of IT” in tamil. Watch it here – https://www.youtube.com/watch?v=a7sMgZZw0CY

Slowly building local tech community. There are many neighbours interested in learnig tech things.
Will do a python workshop for adults.
Will plan for few tech trainings for kids in the upcoming summer break.

Achutha, nithya’s friend is going to give a demo on azure pipeline this saturday evening.

How are you learning new things? If you have any tech people around you, how are you creating a community of learning together? Share your thoughts.

weekly notes 24 2025

As summer is here, the days are long. We are going to nearby park in most of the evenings.
Viyan started to play basket ball. I am also learning it along with him.
Got a kids guitar for him. He started to practise it daily.

On Last saturday saturday, Tamil classes concluded for kids, for this academic year. In this month end, we will get 2 months holidays for kids. There will be more outdoor, park, library visits.

TossConf25 ( Tamil Open Source Conference) is happening next month. July 18,19 2025 at St. Joseph’s Institute of Technology, Chennai. Dont miss it if you are in or around chennai.
Interesting talks and workshops are planned. Book your ticket now here – https://TossConf25.kaniyam.com Thanks for the organizing team for the awesome efforts.

I am collecting huge tamil corpus from around 200+ websites daily. Getting content from RSS feeds are easier than scrapping. But need patience to build the huge text content daily. From 200+ websites, getting around 10 MB text content daily. Colelcting the new words and frequently used words, to build the base
of tamil spellchecker.

I am thinking of hosting one more FreshRSS instance with all these RSS news feeds.
We can read adfree news with RSS Feeds.

On exploring the news websites, found the below things

  • Too many advertisements. Signal to Noise ratio is too high. We will lose interesting reading with this high amount of advertisements.
  • Many websites dont provide RSS feeds. The custom platforms they use dont have RSS feed feature.
  • For few of the wordpress websites, the admin disabled RSS feeds.
  • Few site feeds provide only headings on the feeds.
  • Cloudflare prevents feeds to be read by any feed reader, except the browser.
  • Many writers have their websites, but not writing there frequently. But so active on social media.
    They should atleast keep a copy on their websites,blogs.

    Used the below plugin to get the RSS feed link from the websites. – Rsshub Radar – https://chromewebstore.google.com/detail/rsshub-radar/kefjpfngnndepjbopdmoebkipbgkggaa

Sad to see that Google is showing only 7-8 pages of text content websites. After that, for all queries, we are getting only youtube video links. Whatever we write, google will show only form the mainstream websites.

I am reading more about the copyrights and Rss feeds.
Is it fine to get the full text rss feed and open them all to the public for free reading?

It will be super good to read text without any advertisements, banners, popups, and distractions.
But, the copyright is tricky here. Writers will agree to send their content via email for subscribers, via RSS feed for any personal feed readers. But, may not agree for public feed aggregators.

is it okey to give login credentials for users, to read the content?

I will check with few friends and mentors on what they think.
Reply here on what you are thinking on this.

Here is a screenshot of freshrss shows content from various websites.

Work is going super busy with many new activities. Lot of new learnings on AWS and networking.

Published a video by Nithya on “Basics of IT” in tamil. Watch it here – https://www.youtube.com/watch?v=a7sMgZZw0CY

Slowly building local tech community. There are many neighbours interested in learnig tech things.
Will do a python workshop for adults.
Will plan for few tech trainings for kids in the upcoming summer break.

Achutha, nithya’s friend is going to give a demo on azure pipeline this saturday evening.

How are you learning new things? If you have any tech people around you, how are you creating a community of learning together? Share your thoughts.

Interface

What is an Interface in Java?

Interface in java called blueprint of a class or reference type ,that contains only abstract methods(method without body)(until java 7) and can also contain default/static methods(from java 8)

why interface say reference type in java?

In java reference type means variable does not hold the actual value it is pointing to the object memory. so you can not create object in interface ,but you can use it a reference of the object of a class when implements . like you using class and array

Example:

Vehicle honda = new Car();

Vehicle = interface (or superclass) -> reference type
honda =  variable ( reference variable) -> to point s the object
new car() = object/instace -> Actual object in memory  

why interface called blueprint of a class?

Interface defines what a class should do, not how.
That mean (do) you must have fallow the method name and signature(override) from the interface. (not how) interface does not say what code or logic to write inside that implement method, so interface rule is what should be done but not how ti should be done.

Example:-

interface Vehicle // when implement any class you should override the abstract method but not how.
{
void start(); 
}

class Car implements Vehicle
{
public void start()
{
System.out.println("Car start with key");
}
}  

class Bike implements Vehicle
{
public void start()
{
System.out.println("Bike start with key and kick..etc ");
}
}

public class ShowRoom
{
    public static void main(String[] args) {
Vehicle car1 = new Car(); //interface reference pointing to Car object.
}

}

// must to implement the method
// but not how like whether key or key and kick 

Spring Boot real-world interface used with @Autowired (Loose coupling- does not depend directly ) we will see later.

Why Interface is Called a Contract?

  • You must implement all abstract methods from the interface, otherwise your class will not compile.

  • Interface contain static constants and abstract method. static constants mean all variables in interface by default public static final ,even if you do not write them, it mean fixed value , shared and accessible without object.

interface Contract {
    int VALUE = 100; // same as: public static final int VALUE = 100;
}

Why use Interfaces?

  • To achieve 100% abstraction (before java 8)
  • To support multiple inheritance(java does not support multiple inheritance) Loose coupling between classes used for dependency injection.

Where is Interface used?

  • In real-time projects :- for layers like service ,repository ... etc.
  • In frameworks like Spring, hibernate(e.g JpaRepository, ApplicationContext ..etc
  • In callbacks/event handling (Gui, Threads)
  • In API design: to define method contracts.

How does Interface work?

  • A class implements an interface using implements keyword.
  • The class must to implement(override all methods) for all abstract methods in the interface.

Which types of Interfaces are in Java?

  • Normal Interface - with abstract,default,static methods.
  • Functional Interface -only one abstract method(e.g, Runnable ,Comparable).
  • marker Interface - no methods ,only used to mark like tags (e.g, serializable ,Cloneable)

(we will see interface types upcoming blogs)

Why Interface provides 100% Abstraction (before Java 8)
Interface Rules:-

  • Methods -> By default ,abstract and public
  • variable -> By default , public , static and final.
  • Can not use constructor , instance variable, can not create object
  • class extend one class but class can implements multiple interface(multilevel inheritance)
  • interface extend another interface

In interface implicitly abstract(incomplete method only-No body), you do not need to use abstract keyword when declaring in the interface.
Let see detail information.

1. Abstract method:-

interface Human{
void  eat(); //implicitely public and abstract,you do not nee to mention public abstract.
public abstract void eat(); // same as above

2.Default methods( introduced in java 8)

interface Human{
//  you must to explicit declare the default
// not abstract method
default void  eat()
{
System.out.println("humans are eat veg and non-veg");
} 
//do not define
default void eat(); // not valid 


}

3.static methods(from java 8)
// explicitly declared static
// not abstract.
interface Human{
static void  eat()
{
System.out.println("humans are eat veg and non-veg");
}

4.Private method(java 9+)
// must to declare private
//not abstract method
interface Human{
private void  eat()
{
System.out.println("humans are eat veg and non-veg");
}

4. final in method

Not allowed in interface in final , final mean can not override , interface the main goal is override/implement  to from interface to implemented class . final keyword  can not to use method like abstract, default...etc. Only abstract, default, static, private (from Java 9+) are allowed

//NOW SEE Variables

interface Fruits
{
String fruitName = "Mango";

//above equal to below
public static final String fruitName = "Mango";
}

// you can not declare in interface:-

- private,protected variable not allowed.
- non-static variable(instance field) and method(with body)   not allowed , because you can not create object in interface. 
- protected (only accessible for within  package or subclass,  not for globally) not to allowed to use in interface method,interface method  must to be  access globally   mean like public contract, so protected not to allowed method and variable.
- one more recap , you can not use in  some access  and non access modifier like protected and final and in the method. 




q.1 can we change value of interface variable?
NO, because , by default set final like constant ,can not change the value.

java 7 and before:

An interface only contain:
abstract methods.
Constant(public static final)
This means 100% abstraction- no method in a body

java8 and later:

  • java 8 introduced:
  • default method(with method body)
  • static methods(with method body)

  • so interface now included concrete method ,so interface not anymore 100% abstraction, like abstract classes(Not 100% abstraction)

  • Supports default and static methods.

java 9

you can write private methods inside of interface.

Key points:-

  • Interface and inside of method(in-completed method) is implicitly abstract , you do not need mention.
  • Interface not to allowed to create object.
  • Interface does not contain any constructor.

  • Interface methods are by default abstract and public

- class can extend only one class. Class can implements more than one interface at a time with (,). interface extends more then one interface.

  • Interface attributes(fields or variable) are by default public, static and final => constant

  • Abstract class can implement interface methods

  • interface can not implement or extend a abstract class or normal class.

  • All fields in a interface are public, static, and final by default.

  • All methods in an interface are public and abstract by default (except default, static, and private methods)

.
Rules for overriding methods from interface:-

  1. Method Signature Must Match
  • method name, parameter list , return type must match
  • you can return same type or sub type(covariant return)
interface Parent {
    Number getMoney(); // return type is Number
}

class Child implements Parent {
    public Integer getMoney() { // Integer is a subtype of Number 
        return 1000;
    }
}


2.Checked Exceptions(must to handle ,you can not ignore) Must Be Compatible(only throw same or child exception not unrelated exception):

Interface method throws a checked exception (must be handled, cannot ignore).
When a class overrides that method, it can:

  • Throw the same exception
  • Throw a subclass of that exception
  • Throw nothing (no exception)
  • But cannot throw a new or unrelated checked exception.
we will see example in Exception handling
  1. Implementation Class Can Be Abstract

If class implemets a interface but does not override the abstract method , you can set abstract keyword in class.

Example:-

interface GrandParent {
    void skill();
}

abstract class Parent implements GrandParent {
    // no implementation of skill() — that's okay because Parent is abstract
}

class Child extends Parent  {
    public void skill() {
        System.out.println("Child implemented method");
    }
}

Abstraction

What is Abstraction ?

  • Abstraction means hiding internal details and showing only the essential features to the user.

(or)

  • Abstraction in java is process of hiding implementation details and showing only functionality.

  • abstract is a keyword ,it is non-access modifier , used classes and methods.

  • It tells what an object does, not how it does it.

Achieved using:

  • Abstract classes.( 0% to 100% partial Abstraction and can have both abstract and normal methods )
  • Interface(100% Abstraction -> all methods are abstract by default until java 7). use interface for multiple inheritance.

  • From java 8 onward, interface can have(Interface gives 100% abstraction (before Java 8).):

  • default methods(with body)

  • static methods, so interface not always 100% abstract anymore.

Abstract Class:-

  1. A class with the abstract keyword is called an abstract class.
  2. It can have:
  • Abstract method(without body)
  • Concrete methods(with body)

Abstract classes can have:

  • Abstract methods
  • Concrete (regular) methods
  • Constructors (including parameterized constructors
    
  • If a class has even one abstract method , that class must be abstract.

  • abstract class restricted to Cannot create objects of an abstract class. but subclass extends the abstract class, and you create an object of subclass, the constructor of the abstract class will still run. because sub class object is created ,so the abstract class constructor run first after own class constructor.

  • If child class(any class) inherit(extend) super of abstract class must to implement its abstract methods otherwise that class also abstract class and that class can not create object.
    abstract class can have static and final methods.

  • Abstraction class can contain fields(variable) it helps to initialized through constructors.

Abstract Method:-

  • Declared with the abstract keyword.
  • Abstract method no body , just the method name and a semicolon.
  • That class that contain abstract method it must also be abstract.
  • Any class that inherits the abstract class: must implement the abstract method (must override abstract method )other wise declare the class also abstract.
  • you can not create an object of an abstract class.
  • A subclass must override all abstract methods of an abstract class.
  • Abstract method can have access modifiers like public, protected ,or default(no modifier).
  • But not private ,because the subclass needs access to override it.

Example:-

abstract class Father
{
abstract void  skill(); //abstract method
}


class Child extends Father

void skill(){
System.out.println("I Drawing well the picture ");
}
}

Example:-

abstract class Father
{
abstract void  skill(); //abstract method
}


class Child extends Father
{
    // Did NOT implement skill()
}
// compile time error came 

Example:-

when you send an email , you don not know what happens behind the scenes(protocols,servers). you just type, enter an address, and click send.

  • Abstraction is -> you see what it does, not how it works.

How many abstract methods can an abstract class have?

  • 0,1 or many in abstract class.
  • A abstract method may or may not abstract method even 0 abstract method allowed.

Can we use non-access modifiers like static, final, abstract together?

  • you can combine abstract with public ,protected.

can not use final and abstract and static method can to be abstract.

Can abstract methods have parameters and return types?

yes.

Can we override an abstract method with the same parameters?

yes. that is required , method signature must match.

Can an abstract class have an inner class?

Yes. Abstract classes can have inner classes

Why Interface provides 100% Abstraction (before Java 8)

Why Abstract Class Cannot Achieve 100% Abstraction?

Above 2 question ans in command section

package abstraction;

abstract public class Vehicle {

    // you can use fields private use to getter/setter method (abstraction +Encapsulation)
    String brand;
    int wheels =4;
    final int speedLimit =120;



    //constructor in abstract class
    Vehicle(String brand)
    {
        this.brand = brand;
        System.out.println("Vehicle constructor called");
    }

    // abstract method (must be implemeted in child class)

    // abstract method can use public ,default(no modifer),proctecte
    // can not use abstract method in private,static,final
    abstract void start();

    abstract void carWashing();

    //concreate method

    void stop()
    {
        System.out.println("Vehicle stopped");
    }
    final void fueltype()
    {
        System.out.println("car Fuel type Petrol or Diesel");
    }

    static void info()
    {
        System.out.println("Vehicle are used for transport");
    }
    public static void main(String[] args) {

        //Vehicle vehicle1 = new Vehicle();  object can not created in abstract class in core concept java incomplemetd  method in class can not create object .
    }
}



// child class



package abstraction;

abstract public class Vehicle {

    // you can use fields private use to getter/setter method (abstraction +Encapsulation)
    String brand;
    int wheels =4;
    final int speedLimit =120;



    //constructor in abstract class
    Vehicle(String brand)
    {
        this.brand = brand;
        System.out.println("Vehicle constructor called");
    }

    // abstract method (must be implemeted in child class)

    // abstract method can use public ,default(no modifer),proctecte
    // can not use abstract method in private,static,final
    abstract void start();

    abstract void carWashing();

    //concreate method

    void stop()
    {
        System.out.println("Vehicle stopped");
    }
    final void fueltype()
    {
        System.out.println("car Fuel type Petrol or Diesel");
    }

    static void info()
    {
        System.out.println("Vehicle are used for transport");
    }
    public static void main(String[] args) {

        //Vehicle vehicle1 = new Vehicle();  object can not created in abstract class in core concept java incomplemetd  method in class can not create object .
    }
}



Encapsulation

What is Encapsulation ?

  • Encapsulation is the process of wrapping data(variables) and code (methods) together as a single unit . It hides the internal state of object from outside access, that mean the variable of a class will be hidden from other classes, and can be accessed only through method of current class. Encapsulation used to achieve data hiding ,not itself data hiding.

Why Use Encapsulation

  • protects Data : keep important Fields are private (data-variable) safe from direct access.
  • Hides Details : show only necessary thins to the user
  • Controls Access:- gives control over who can read or change the data. that mean you can lock you data using private and you give a key (get/set method) to trusted one,only change authorized class or user.
  • Easy to change: you can change the code inside without affecting other code and also you can use another project Encapsulated project

Achieving Encapsulation in java:-

Declare the variables of a class as private.
provide public setters(write-only) and getters(read-only) methods to modify and view the variables values.

Benefits of Encapsulation:-
The fields(global variable ) of class can be made read-only (or) write-only. class can have total control over what is stored in the fields.

Example:-

package encapsulation;

public class BankAccount {

    // private variable - hidden from outside
    private  String  accountHolderName;
    private int accountNumber;
    private double balance;



    // constructor
    BankAccount(String name ,int accNumber, double initialBalance)

    {
        this.accountHolderName=name;
        this.accountNumber=accNumber;
        if (initialBalance >=0)
        {
        this.balance=initialBalance;

        }
        else
        {
            System.out.println("Invalid blance! setto 0 by default. ");
            this.balance=0;
        }
    }

    public String getAccountHolderName()
    {
        return accountHolderName;
    }

    public void setAccountHolderName(String name)
    {
        if (name != null && !name.isEmpty())
        {
    this.accountHolderName= name;
        }else
        {
            System.out.println("Invalid name!");

        }
    }
    // Get balance (no direct access to variable)
    public double getBalance()
    {

        return balance;
    }
    // withdraw method with check
    public void deposit(double amount)
    {
        if (amount > 0 )
        {
            balance += amount;
            System.out.println("Deposited: "+ amount);
        }
        else {
            System.out.println("Invalid deposite amount!   ");

        }
    }

    // deposit method with validation
    public void withdraw (double amount)
    {
    if (amount > 0 &&amount <= balance)
    {

        balance -= amount;
        System.out.println(" Withdrawn:"+ amount);
    }
    else
    {
        System.out.println("Invalid funds");
    }
    }

    //Display details (read-only)

    public void displayAccountInfo()
    {
        System.out.println("Account Holder: "+ accountHolderName);
        System.out.println("Account Number: "+ accountNumber );
        System.out.println("Current Balance: "+ balance);


    }

}



package encapsulation;

public class Bank_Main {

    public static void main(String[] args) {


        BankAccount account = new BankAccount("Prasanth",1001,5000);

    account.displayAccountInfo();
    account.deposit(1500);
    account.displayAccountInfo();



    //Trying to withdraw
    account.withdraw(1500);
    account.displayAccountInfo();



    //trying to withdraw
    account.withdraw(2000);
    account.displayAccountInfo();

    // Trying to set a bad name
    account.setAccountHolderName("");
    account.setAccountHolderName("sam");
    System.out.println("updated name:" +account.getAccountHolderName());


    //trying invalid operations
    account.deposit(-500);
    account.withdraw(10000); //more than balance

    }



}

Encapsulation Read-only class

Example:2

package encapsulation;

// Creating Write-Only Class
public class FruitShop {

    private String fruitname;
    private int fruitprice;

    public  void setName(String name)
    {
        this.fruitname=name;

    }

    public void  setfruitPrice(int price)
    {
        this.fruitprice=price;
    }
}


package encapsulation;

// Creating Write-Only Class
public class FruitShop {

    private String fruitname;
    private int fruitprice;

    public  void setName(String name)
    {
        this.fruitname=name;

    }

    public void  setfruitPrice(int price)
    {
        this.fruitprice=price;
    }
}


Read and write:-

package encapsulation;

public class TechwaveEmployee {

    private String emp_name;
    private String  emp_id;
    private double net_salary;

    TechwaveEmployee(String emp_name,String emp_id ,double net_salary)
    {
        this.emp_name =emp_name;
        this.emp_id = emp_id;
        this.net_salary = net_salary;
    }

    public String getEmp_name() {
        return emp_name;
    }

    public void setEmp_name(String emp_name) {
        this.emp_name = emp_name;
    }

    public String getEmp_id() {
        return emp_id;
    }

    public void setEmp_id(String emp_id) {
        this.emp_id = emp_id;
    }

    public double getNet_salary() {
        return net_salary;
    }

    public void setNet_salary(double net_salary) {
        this.net_salary = net_salary;
    }
}




package encapsulation;

public class TechWaveHr {

    public static void main(String[] args) {

        // first object - setting values using constructor
        TechwaveEmployee person1 = new TechwaveEmployee("Prasanth","Empl001",15000.00);

        TechWaveHr person2 =  new TechWaveHr();

        // printing data
        System.out.println("Employee (Initial values):");
        System.out.println(person1.getEmp_id()+ " , "+ person1.getEmp_name()+" ," + person1.getNet_salary());

        // updating values setter methods
        person1.setEmp_id("Empl002");
        person1.setEmp_name("Vishal");
        person1.setNet_salary(50000.00);


        //printing data

        // printing data
                System.out.println("Employee (Updated values):");
                System.out.println(person1.getEmp_id()+ " , "+ person1.getEmp_name()+" ," + person1.getNet_salary());

    }

}



Polymorphism

what is Polymorphism?

  • It is a feature of object oriented programming(oops)
  • polymorphism means "many forms". It allow a method(method overloading & overriding) or object(static & dynamic binding) to behave in multiple ways,depending on the context or usage or situation.

Types Of Polymorphism:-

1.Compile-Time Polymorphism (static Binding/method overloading)

  • when a class has two or more same method name , different parameter list is called compile-time Polymorphism.Binding type Static binding.

Example:-

package polymorphism;


//Method Overloading: Different Number of Arguments 
public class Calculator {


    public int addTwoElements(int a , int b)
    {
        return a+b;

    }

    public int addThreeElemets(int a , int b ,int c)

    {
        return a+b+c;

    }

    // Method Overloading: Different Type of Arguments
    public static int  multiply(int a ,int b)

    {

        return a*b;
    }

    public static double division(double a ,double b)

    {

        return a/b;

    }
    // can not  overloaded if you different return type 
    //int add(int a, int b) { return a + b; }
    //double add(int a, int b) { return a + b; } 


    /*
     * can’t overload by changing between static and non-static?
     * 
     * static void display(int a) {}
    void display(int a) {}  //
     * 
     * 
     */
    public static void main(String args[])
    {
        Calculator  cal = new Calculator();

        System.out.println(cal.addThreeElemets(1, 2, 3));
        System.out.println(cal.addTwoElements(10, 20));
        System.out.println(multiply(10,5));   
        System.out.println(division(10,5));


    }

}




2.Run-Time Polymorphism(Dynamic Binding / Method overriding)

  • Same method name and signature ,different class (child class overrides parent ) is called method overriding
  • Decided at runtime,Binding type: Dynamic binding.
  • Method overriding is for achieving run-time polymorphism.

Rules of Method overriding:-

  1. same arguments - the method in child class must have same parameter as in the parent class. 2.same or compatible return type
  • return type must be the same or subclass of the parent method return type(subclass method must match the parent class method's name, parameters, and return type. ).

3.Access level not more restrictive:-
The child method can not have lower access level than the parent.

example:-

  • if parent method is public ,child method can not be private or protected.

4.Must be inherited
only the methods that are inherited by the child class can be overridden.

  1. final & private methods can not be overridden
  2. static method can not be overridden ,you can re-declared but not overridden.

7.same package -more freedom

if the child class is in same package ,it can override all methods except private or final ones.

8.Different package -less freedom

If the child is different package , it can only override public or protected methods(not default/package-private)

9.Constructors can not be overridden
constructor can not inherited ,so they can not be overridden.(constructor is implicitly final)

10.Exception -overriding rule [TBD]

  • The child method can throw unchecked exceptions freely.
  • It can throw fewer or narrower checked exceptions, but not broader ones.

How to used:-

parent class reference can be used to refer to a child class object , this helps to you code flexible and reusable code.


About reference variable:-

  • Every object is accessed through a reference variable. it is a fixed type ,once you created you can not to be changed , it can refer own type or subclass object ,it can be class type or interface type. this type reference to decide what method can be accessed.

Example:-

package polymorphism;

public class Animal {

    void sound()
    {
        System.out.println("Animal makes a sound");
    }


    void type()
    {
        System.out.println("This is a general animal");
    }
}



package polymorphism;

public class Dog extends  Animal {


    void sound()
    {
                super.sound();// Method Overriding: Using the super Keyword
        System.out.println("Dog barks");
    }
    void guard()
    {
        System.out.println("Dog gurads the house");
    }

    public static void main(String[] args) {

        Animal a;

        a = new Dog();
        a.sound();
        a.type();
    //  a.guard(); not allowed only override method only allowed 
        Dog c = (Dog) a;
        c.guard();
    }

}

package polymorphism;

public class Cat extends Animal {

    void sound()
    {
        System.out.println("cat meow");
    }
    void work()
    {
        System.out.println(" catching the mouse and  sleep a  lot");

    }
    public static void main(String[] args) {

        Animal a;

        a = new Cat();
        a.sound();
        a.type();
        //a.work(); only allowed Animal override in cat class
}


}

Dynamic Binding (Run time Polymorphism)

  • Dynamic binding means method call is resolved at runtime based on the object type ,not reference type.
//superclass 

public class Water_Animals {

    public void move()
    {
        System.out.println("water animal swim in sea");
    }
    public void foodType()
    {
        System.out.println("water animal eithter veg or non_veg");
    }

}

// sub class  

package polymorphism;

public class Shark  extends Water_Animals {

    @Override
    public void move()
    {
        System.out.println("i move faster to and hungry hunter of sea");

    }

    @Override
    public void foodType()
    {
        System.out.println("i eat Non-Veg all time");
    }
    public static void main(String args[]) {


        Water_Animals wa = new Water_Animals(); // normal object (only  access method/variables  Water_Animals)
        Shark  shark = new Shark(); // normal object ,Can access both Shark and inherited Water_Animals non-static members
        Water_Animals waterAnimal = new Shark (); //upcasting(Child object, Parent reference), You can access only methods/variables declared in Water_Animals, Cannot access Shark-specific methods/fields unless overridden
         Shark  sh = (Shark) waterAnimal;
         //Downcasting (Parent reference cast back to Child),You can now access both Water_Animals and Shark members

// (water_Animal  reference )water_Animal wateranimal = new Shark()  // Shark object

    }


}

When: Happen at runtime
used IN: Method overriding
Resolves: Based on actual object(not reference type)
Other Names : Run-time polymorphism/late binding.

Static Binding:-

  • Static Binding also called compile time or Early Binding it means call is decide by the compiler at compile time ,not a runtime. Based on Reference type and method signature. used in method overloading. method types happen static,final , private , non-static or overloaded methods ( same class happen).
  • performance faster than dynamic binding.

Java Inheritance

what is Inheritance ?

  • In Java , It is to inherit attributes and methods from one class(super class) to another class(sub class).
  • subclass(child/derived) - the class that inherits from another class.
  • super-class (parent/base) - the class being inherited from
  • To inherit from a class, use the extends keyword.

why to use ?

  • It useful for code re-usability; reuse attributes(fields) and methods of an existing class when you create a new class.
  • If you don not want other classes to inherit a class, use the final keyword.

Need of java inheritance:-

Code Re Usability:-

The code written super class you can not re write subclass it is common for all sub class ,child can directly use the parent properties(fields& properties)

Method overriding:-

method overriding : super class extends sub class ,the sub class inherit properties of parent class.
inheritance, this one of the way archive the run time polymorphism.

Abstraction

The concept of abstraction do not provide detail info in super class ,you need to implement your subclass,if you do not implement that subclass also Abstract class and you can not create object,so Abstraction achieve with inheritance.

how to inheritance work:-

  • The extends keywords is used for inheritance in java. it enables the subclass inherit fields and methods(override) from the super class unless those properties private and also subclass add new methods.
  • The extends keyword is used for establishes an " is-an relationship between child and parent class

Example:-

package oOps_Inheritance;

public class Calculation {

    int z;

    public void  addition(int x ,int y)
    {
        z = x+y;
        System.out.println("The sum of given number: "+z);
    }

    public void subtraction(int x, int y)
    {
        z= x-y;
        System.out.println("The subtraction of given number: "+z);
    }


}

package oOps_Inheritance;

public class My_Calculation extends Calculation{

    public void multiplication(int x,int y)
    {
        z = x* y;
        System.out.println("The sum of multiplication:  "+z);
    }


    public static void main(String[] args) {

        int a =20, b=10;
        My_Calculation calculate = new My_Calculation();
        calculate.addition(a, b);
        calculate.subtraction(a, b);
        calculate.multiplication(a, b);


    }

}

Note:-

  • subclass get everything from superclass(fields and methods) except constructors.if you used private members not accessed in subclass. From Superclass Protected fields and methods can access in the subclass(even other package)and same package.
  • when you create an object of the subclass ,it also includes the members of superclass.
  • you can use a super class reference to hold a subclass object , but it only access to super class members not a sub class members.Constructor not inherited/override , you can use the super() call the parent class constructor first line of the child constructor (when you create object in child first parent executed after to child constructor executed =>constructor chaining )and also you can call or access non-static fields and methods to call using super().
Parent p = new Child(); //  Upcasting
p.superClassMethod();   //  Allowed
p.childMethod();        // Not allowed directly

  • If you want to access both superclass and subclass methods, use a subclass reference.
Child c = new Child();
c.superClassMethod();  // 
c.childMethod();       // 

But if you create a parent class reference and store a child class object , you can access only the parent class members, not child class members.

Example-2:-

package oOps_Inheritance;

public class Animal_SuperClass {
    String name;
    public void eat()
    {
        System.out.println("I can eat ");
    }

    //Note: protected methods  and fields  only accessible from the subclass of the class.

  // why to use inherittance
    /*
     * code reusability
     * Achive to(polymorphism & Abstraction)
     * method overriding  
     * 
     * 
     */
}

package oOps_Inheritance;

public class Lion extends Animal_SuperClass {

    @Override
    public void eat() {
        super.eat();
        System.out.println("I can eat non-veg");
    }

    public void infoDisplay()
    {
        System.err.println("My name is "+name);

    }

    public static void main(String[] args)
    {
        Lion lion = new Lion();
        lion.name = "prasanth";
        lion.eat();
        lion.infoDisplay();
    }

}


Types of Inheritance in java:-

- single Inheritance

single Inheritance , a single subclass extends from a single superclass.

Example:-

Example-2:-

- Multilevel Inheritance

The inheritance in which a base class inherited to a to derived class(subclass) and that derived class inherited to another derived class is known as multilevel inheritance.

Example:-

package oOps_Inheritance;

public class Animal_SuperClass {
    String name;
    public void eat()
    {
        System.out.println("I can eat ");
    }

    //Note: protected methods  and fields  only accessible from the subclass of the class.

  // why to use inherittance
    /*
     * code reusability
     * Achive to(polymorphism & Abstraction)
     * method overriding  
     * 
     * 
     */
}

// sub class

package oOps_Inheritance;

public class Lion extends Animal_SuperClass {

     String position ;
String name = "Likera";


    @Override
    public void eat() {
        super.eat();
        System.out.println("I can eat non-veg");
    }

    public void infoDisplay()
    {

        System.err.println("My name is "+name+" .I am king of the jungle");

    }

    public static void main(String[] args)
    {
        Lion lion = new Lion();

        lion.position="King";
        lion.eat();
        lion.infoDisplay();
    }

}

// derived class extend another derived class.

package oOps_Inheritance;

public class Lion_Cub extends Lion  {
    String cubName;

    @Override
    public void infoDisplay()
    {
        super.infoDisplay();
        cubName="simba";
        System.err.println(cubName+" : My father name is "+name);

    }



    public static void main(String[] args) {

        Lion_Cub  cub = new Lion_Cub();
        cub.position="Secound-King";
        cub.infoDisplay();


    }

}



Structure:-

grandpa(murgan.m)
|
V
son(Ravi.m)
|
V
child(RaviChild-prasanth.R)

- Hierarchical Inheritance:-

The hierarchical inheritance one base class(super class) extend multiple derived class(subclass) is known as hierarchical inheritance.

public class Murgan_SuperClass {

    public static String name = "Murgan";

    public void skillOne()
    {
        System.out.println("MySkill is Drawing well the picture");

    }
    public void skillTwo()
    {
        System.out.println("MySkill is Kig-Boxing chapion");

    }

}


package oOps_Inheritance;

public class Ravi_SubClass  extends  Murgan_SuperClass{

    public static void main(String[] args) {
        Ravi_SubClass  ravi = new Ravi_SubClass();
        System.out.println("my fathe name is "+Murgan_SuperClass.name);
        ravi.skillOne();

    }

}

package oOps_Inheritance;

public class Kumar_SubClass  extends Murgan_SuperClass{

    public static void main(String[] args) {

        Kumar_SubClass kumar = new Kumar_SubClass();
        System.out.println("my fathe name is "+Murgan_SuperClass.name);
        kumar.skillTwo();

    }

}


Structure

Fateher(Murgan) ---------> Ravi(subclass)
|                (extends)
| (extends)      
V
Kumar(sublclass)

- Multiple Inheritance:-

  • Multiple Inheritance is a one class have a more then one super class and inherit features from all parents classes.
  • Java does not support the multiple inheritance only to achieve to the interface.

Example-syntax:-


interface Coder
{
//code
}

interface Tester
{
//code
}


class DevopsEngineer  implements  Tester,Coder
{

// override methods from interface
//programme logic
}

Structure:-

Ravi(father)    Kanimozhi(mother) 
     |             |
     | (implements)|  
     v             V
     R.prasanth(son) 

why not support multiple inheritance ?

Java does not support with multiple inheritance with class why? reason is to avoid Diamond/Ambiguity problem

Hybrid Inheritance in Java:-

Single Inheritance + Hierarchical Inheritance = Hybrid Inheritance;

Upcasting and Downcasting in Java


Parent p = new Child(); //  Upcasting
p.superClassMethod();   // Allowed
p.childMethod();        // Not allowed directly
Parent p = new Child(); // Upcasting
Child  c = (Child) p;        // down casting
c.superClassMethod();   // Allowed
c.childMethod();        //   allowed directly

// above only instance member only ,object is instance related.

Parent p = new Parent();    // p holds Parent object only
Child c = (Child) p;        //  Runtime Error: ClassCastException!

Reason : compiler allow  because casting is ok , but run time  jvm see that that object not a chile so
it thorws.

Exception in thread "main" java.lang.ClassCastException: Parent cannot be cast to Child



Resolution Time(which method/variable to use for compile or runtime)

Compile Time – Before running the program =>java compiler check method/variable decide which one to call.
Run Time -> JVM decides which method to execute based on the object. when the program running

Image description

Why Java resolve instance methods at runtime,
but variables (static & non-static) and static methods at compile time?

static type memory allocated once in memory , when at complile time/load time , who control ? JVM class loader.
instance type is new memory for each object at run time , who control it ? jvm during object creation.

1.Why are instance methods resolved at runtime?

when call instace method obj.run() java wait until the programm running ,to check or decide whic method to call because child can override parent method like who really created parent or child that all.

2.Why are variables (even non-static) resolved at compile-time?
when you use a variable obj.var1 which variable to use at compile time , based on the reference type,not a object , because methods only override not a variable.

3.Why are static methods and static variables resolved at compile-time?

static method/variable pointing to class not a object. loaded once when class loads.
(static method overriden)

what is class loader in java ?

A class loader is part of JRE ,that is responsible for loading .class files into memory when you programm runs. like you write java .java file compile to .class file JVM need it to run class loader it into memory

Access modifier

What is modifiers?

  • Java access modifiers are used to specify the scope of variable,constructor,class,methods,data members. it is helps to restrict the and secure the access.

Type:-

  • Access Modifier.
  • Non-Access Modifiers

Access Modifier:-

Image description

  • default − Visible to the same package. No modifiers are needed.
  • private − Visible to the class only.
  • public − Visible to the world.
  • protected − Visible to the same package and all sub classes.

Access Modifiers:-

  • for classes, you can use either public (or) default main class you can use and inner class you can use all access modifier).
  • for attributes(fields),methods,constructors for public,private,default ,protected.

Non-Access Modifiers:-

  • for class you can use final or abstract
  • In final have class can not be inherited(extend) by other classes.
  • abstract - The class can not be used to create object (To access an abstract class ,it must be inherited (extend) from another class, you must implement abstract method from parent to child class other wise child class can not create object and this child class also abstract class)

for attributes(fields) and method :

  • final method/fileds can not be overridden.
  • static method can be overloaded and can not be overridden.

  • In fields can be static,final and access modifier ,final in fields(global variable) once initialize the variable can not be reinitialize.

  • construct you can use access modifier and final only you can use and can not to be static and abstract.parameter not allowed access modifier and only final only.

  • Abstract class only to use to abstract method,the method does not have body. Abstract method be overridden.

  • Abstract method can not to be static ,main purpose abstract method created object from inherited class(child class). static means no object needed.you can define static method in abstract class.
    -transient,synchronized,volatile

Package in java :-

  • A package is a folder that group related classes together.
  • why use packages?
  • To organize code,To avoid name conflicts,To reuse classes easily.

Type casting

What is typecasting ?

  • Type typecasting is a converting one data type to another data type in java ,used either compiler or programmer , for example: converting int to double, double to int.
  • Type casting also know as type conversion.

Types of casting:-

  • widening type casting(java)
  • Narrowing type casting(programmer)

Primitive typecasting:-

widening type casting(java):-

widening type casting is also know as implicitly type conversion like ,The process converting smaller type (int) to lager type,This job done by compiler automatically( Java compiler uses the predefined library function for transforming the variables). The conversion done time compile time.

Never data loss.

Hierarchy:-

byte->short->char->int->long->float->double. 

Example:-

/widening type casting
public class Tester {

    public static void main(String[] args) {

        int num1 =501;
        double num2=2.5;
        double sum = num1 +num2; // typeconvertion done by java.

        System.out.println("The sum of "+num1+ " and "+num2+" is "+sum);

    }

}


Narrow type casting:-

Narrow type casting is also know explicit type casting or explicit type conversion.this conversion done by programmer manually,this type conversion converting larger type to smaller type.if do not do manually compile time error will occur.

Hierarchy:-

double -> float -> long -> int -> char -> short -> byte

Example:-

public class Narrowing_Test2 {

    public static void main(String[] args) {

        int num =501;

        //type casting int to double
        double doubleNum = (double) num;

        System.out.println("Type casting int to double: "+doubleNum);

        //type casting   double to  int
       // possible  data loss in narrowing casting , because is can  not hold larger data to small type data type                           
        int   num2 = (int) doubleNum;

        System.out.println("Type casting   double to int: "+num2);


    }

}
  • Can not auto convert(not compatible ) to/from boolean with number types.

  • char can be cast to/from int,but explicitly.

we will see explicit Upcasting and Downcasting in inheritance:-

In inheritance(object typecasting):-

what is Upcasting?

  • Converting a child class object to parent class reference.
  • Done implicitly (automatically)
  • No typecasting needed
  • Safe and not possible data loss
 Dog d = new Dog(); //child class object 
Animal a = d;  // Upcasting (automatic)

what is Downcasting?

  • Converting a parent class reference to a child class reference.
  • Done explicitly(manually)
  • you must need type cast.
  • Error occurred if do not done manually throw the ClassCastException.
Animal a = new  Dog (); // upcasting
Dog d = (Dog) a ; //downcasting (manual)

Logical program -1 -> read the number from standard input using scanner and another without scanner class

Program-1:

package logicProgramme;

import java.util.Scanner;

public class Scanner_Class_ReadIntegerValue {


// read the number from standard input 

    public static void main(String[] args) {
        int num;
        // print the message to ask the user to enter number
        System.out.println("Enter the integer: ");

        // Scanner class import from utility package.
        //create Scanner object. 
        Scanner  s = new Scanner(System.in);
        //create scanner object s ,to take input from keyboard (System.in)

        //read the input form the user and store it  in num.
        num = s.nextInt();

        System.out.println("Entered interger is: "+ num);

        // closes the scanner to free up the resourse.
        s.close();


    }

}

Program-2

package logicProgramme;

public class ReadInetegerWithoutScanner {


    // read the number from  without scanner class


    public static void main(String[] args) {
    if (args.length >0) // check the  user entered input or no.
    {
        int num =Integer.parseInt(args[0]);
        // Integer.parseInt(args[0]); , Integer.parseInt -> it is convert  string to integer, args[0] , index of  array 0 the postion take the input 
        // parse mean read and  convert , int means integer - string to int convert 
        // example:-i entered arg tab 123 and it String args output 45  
        // in eclipse right click file -> runs as -> run configuration -> argument tab  give nput and apply and run.

        // simple Integer ,java class  in java.lang package parseInt
        //Integer -> class ,  parseInt method,

        System.out.println("Entered integer is: "+num);
    }
    else
    {
        System.out.println("No integer entered");
    }
    }

}

/*int to String convert 
 * String.valueof();
 * 
 * 
 * /
 */

Example:3-

package logicProgramme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class UsingBufferedReaderClass {
// how to use BufferReader to read a line of input from the user and print it to the console.
    public static void main(String[] args) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String input  =reader.readLine();

        System.out.println(input);


    }

}
/*
 * 1.Bufferedreader -> Bufferedreader in java class read the text from the charater(not byte )  input stream. 
 * 
 * system.in read the byte from the keyboard  not characters.(system.in  can not directely  read string or line -only raw bytes)
 * 
 *2.InputStreamReader -> it is a bridge b/w System.in (bytes)  and java character
 * it is convert to  byte to character, so help full for  read text from keyboard.
 * 
 * 3.readline() it method  of Bufferereader, it ead one full line of text and it is return a string 
 */

/*BufferedReader it  java class read the text chracter not bytes, system.in  , 
 * it read  input from keyboard like byte not a character, Inputstreamreader is it help convert byte to character ,and read text in keyboard and , it bridge b/w  (system.in)  byte and character, and readLine() methdod of  Bufferereader class,it reade the  text line
 * 
 * 
 */

Variable

what is Variable?

Variable(named memory location )are containers for storing data values.like number,words,or object,Each variables has a specific type ,it determines the size and layout of variable memory.

java keywords:-

java has a set of keywords that are reserved words that can not to used as variables,methods,classes or any other identifiers

Example:-

String nation="India";

String is keyword ,it indicates that the nation variable of String data type ,that variable hold string value particular memory location.

some keywords:-
abstract,int,byte,boolean,class,do,else,extedns,final,if,while....etc

what is identifier:-

Identifier in java is the name used to identify a class,interface,methods,variables,constructor,package...etc

only allowed to java is naming rules class,interface,methods,variables,constructor,package...etc

Rules with Naming Conventions:-

  • start with lowercase,then capital words.example studentName, rollNO.
  • Should be meaningful
  • can to be keyword.
  • avoid to $ and _
  • Can not start with digit and can contain letters
  • No space and symbols

Variable Declaration and initialization

you must declare all variables before the can be used. variables are declared by specifying data type depend upon the variable name.

syntax:-

<data_type> <variable_name> = <value>;

Example:

int a, b, c; // Declare variable (int data type, a,b,c variables)
int a = 10, b = 10; // value initialization
double pi = 3.14159; // declares and assigns a value
char a = 'a';
String name = "Prasanth";

Types:

Local variable:

  • Local variable declared inside the the body of method (including parameter method),constructor or block is called local variable and only visible inside not to be outer . you can use only this variable only with in the method and the other method do not aware that the variable is exit.It is a combination of "vary + able" which means its value can be changed.

  • Local variable there is no default value for local variables, so local variables should be declared and an initial value before first use.

  • Local variable can not be define with the static and other access modifier only allowed to final.

  • when method starts ,memory is given to local variable and method ends ,that automatically removed. Jvm is handle the memory allocation to local variable and when method start or called it stored(Location) or allocated stack memory ,method ends(Life time) stack frame is removed and local variable automatically destroyed.

  • scope means: where the variable can be used or accessed.

Instance Variable:-

  • Instance variables are known as non-static variables and are declared and visible(access modifier) in a class outside of any method,constructor,block.instance variable created when object is created.each object of the class has its own copy of instance variables.
  • you can use instance variable to access modifier unless it has default access modifier.Initialization of an instance variable not mandatory if you not initialization variable default value provide,dependent on the data type of variable.instance variable can be accessed only by creating object.instance variable are used ,when you need to share values b/w multiple methods or blocks in class and instance variable access to class level .
  • instance variable directly access or use the inside of instance variable without any reference and static method when you need to access or use you need to create object for example you need to object reference.variable name .
  • you can use initialization instance variable using constructor and instance blocks.
  • (Lifetime)
  • Memory for instance variable is allocated when object is created and memory is freed when object is destroyed
  • space allocated or memory location = an object in the heap.

Manage by = jvm - Garage collector

static Variable:-

  • static variable declared with the static keyword in a class, but outside method and constructor or a block.
  • Each variable are only one copy per class ,no matter how many object create from.
  • static variable rarely used to declaring constant (static+final), once you set can not to be change the initial value and static variable stored int static memory.

Example:

public class Car
{

public static final String  color= "red";
   public static void main(String args[]) {

String color = "orange";
}}

  • static variable are created or memory allocated when the programs starts ,when stop the programme stopped.
  • visibility similar to instance variable.
  • static variable Default value same as instance variable ,variey default values it depends upon datatype what you used in the variable.
  • static variable can be accessed by calling with class name Classname.Variablename or without class. without class name access static variable the compiler will automatically append the class name, but accessing static variable different class you must to mention classname.
  • you can access a static variable like instance variable to the object , but compiler will show warning message and it is not affect the program
  • static variable can not declare locally like inside method.and also static block can be used to initialize static variable.

Note:-

  • static variable share one copy for all object ,if changed ,it affect all
  • Non-static variable gives each object is own copy ,if changed anything one ,it not affect all.

we will see the program in upcoming blogs

Weekly notes 22 2025

Missed weekly notes for few weeks. Got some interesting days. I reduced the time spent on facebook, twitter, instagram and youtube.
Wanted to work on some long year dreams. I am happy on the progress. Still have to do a lot on these. But giving a start itself a good thing.

  • Working on word lookup based spellchecker for tamil language.
    Implemented bloom filter, bk tree based search/suggestion solution.
    Need to improve with error free tamil words.
    Collecting good words from available tamil datasets.
    May have to work on applying few grammar rules.
    It is a long dream to bring a open source tamil spellcheker.
    Giving some time and focus to work on the dreams.

    see the POC demo here – https://iyal.kaniyam.ca/
    It is just a POC. there are tons of things to improve.
    Stay tuned or contribute, to see the changes.
  • I want to reduce the content consumption from social media.
    But still want to read the content by beloved writers and bloggers.
    Fortunately, few of them are still writing in their blogs, websites and online magazines.
    Collected the websites of the tamil writers, publishers, literary magazines.
    Hosted a FreshRSS instance here – https://reader.kaniyam.ca/
    You can also read good tamil content here daily, without any advertisements, promotions, algorithms.

    Let me know if we can add any more tamil sites that are related to literature and technology.
    The only requirement is that the website should provide RSS feeds.
    Sad to know that many webmasters are removing the RSS feeds from their sites.
    Please enable RSS feed in your blogs and websites, so that the content will reach many readers.
  • As I am exploring many websites for good tamil content, found that many websites disappeared from the internet. One of the major reason is missing of domain renewals. we give some email id when registering the domains. But, we switch emails very often. When we get email alerts on the email accounts that we never check, we loss the domains. Working on a dashboard to show the list of domains and their expiry dates. Thanks to python, prometheus and grafana.
    Added around 200 domains to the monitoring list, which I know the persons who manage the domains. I am sending them private messages in whatsapp or telegram or email reminding to renew. Will try to automate the notification. Let me know if you like to add your or any domain to monitoring list.
  • Will release all the code for all of the above this week.
  • Many of my friends are worrying about the future of IT jobs. The recent AI tools are generating good code. Will they lead to human losing the technical jobs? I expect the same. There will be change always. We have to keep on learning new things and be ready to do any kind of job.
    The days of doing same role for many years are gone. In future, we all should be knowing backend, frontend, database, deployment tools. Interesting days are on the way. Be open to learning new things.
  • Nithya released 4th video on GenAI series in Tamil – Next word prediction using LSTM – see it here – https://www.youtube.com/watch?v=-f0QMUOdfOg
  • Tamil Open Source Conference 2025 is happening next month, in chennai. Check the details here – https://TossConf25.kaniyam.com

    Call for speakers is here – https://forums.tamillinuxcommunity.org/t/tossconf25-call-for-speakers/2913
  • On Saturday’s Tamil Grammar meetings, we are working on writing python code for tamil grammar rules using the very old book Tolkappiyam. Join and contribute, if you like to help for tamil language.
  • On Sundays, we meet at Kanchi Linux Users Group online meetings and discuss various open source things. We mentor students and job seekers to do some projects. Dont miss these meetings, to dive into older and modern technologies.
  • All our events are listed in the calendar at https://kaniyam.com/events subscribe to the google calendar there using computer. Thanks to Vanaja for curating all the events and publishing there.
  • Syed Jafer from parottasalna.com is one of the passionate FOSS contributor. He is a good trainer on Python, redis, data structures, git etc. He started a forum to discuss tech things. Post your questions here – https://forums.parottasalna.com/ Happy to see many forums are being built. Contribute to the open forums, open websites and keep them active and alive.
  • Books completed – சமயங்களின் அரசியல் – தொ. பரமசிவன். , ஓம் ஷன்ரிக்கியோ – பா. ராகவன்
  • Currently reading – What the internet is doing to our brains – The Shallows – by Nicholas Carr
  • What are you doing interestingly? Write them on your blog as individual blogs or as weekly notes like this.

Weekly notes 22 2025

Missed weekly notes for few weeks. Got some interesting days. I reduced the time spent on facebook, twitter, instagram and youtube.
Wanted to work on some long year dreams. I am happy on the progress. Still have to do a lot on these. But giving a start itself a good thing.

  • Working on word lookup based spellchecker for tamil language.
    Implemented bloom filter, bk tree based search/suggestion solution.
    Need to improve with error free tamil words.
    Collecting good words from available tamil datasets.
    May have to work on applying few grammar rules.
    It is a long dream to bring a open source tamil spellcheker.
    Giving some time and focus to work on the dreams.

    see the POC demo here – https://iyal.kaniyam.ca/
    It is just a POC. there are tons of things to improve.
    Stay tuned or contribute, to see the changes.
  • I want to reduce the content consumption from social media.
    But still want to read the content by beloved writers and bloggers.
    Fortunately, few of them are still writing in their blogs, websites and online magazines.
    Collected the websites of the tamil writers, publishers, literary magazines.
    Hosted a FreshRSS instance here – https://reader.kaniyam.ca/
    You can also read good tamil content here daily, without any advertisements, promotions, algorithms.

    Let me know if we can add any more tamil sites that are related to literature and technology.
    The only requirement is that the website should provide RSS feeds.
    Sad to know that many webmasters are removing the RSS feeds from their sites.
    Please enable RSS feed in your blogs and websites, so that the content will reach many readers.
  • As I am exploring many websites for good tamil content, found that many websites disappeared from the internet. One of the major reason is missing of domain renewals. we give some email id when registering the domains. But, we switch emails very often. When we get email alerts on the email accounts that we never check, we loss the domains. Working on a dashboard to show the list of domains and their expiry dates. Thanks to python, prometheus and grafana.
    Added around 200 domains to the monitoring list, which I know the persons who manage the domains. I am sending them private messages in whatsapp or telegram or email reminding to renew. Will try to automate the notification. Let me know if you like to add your or any domain to monitoring list.
  • Will release all the code for all of the above this week.
  • Many of my friends are worrying about the future of IT jobs. The recent AI tools are generating good code. Will they lead to human losing the technical jobs? I expect the same. There will be change always. We have to keep on learning new things and be ready to do any kind of job.
    The days of doing same role for many years are gone. In future, we all should be knowing backend, frontend, database, deployment tools. Interesting days are on the way. Be open to learning new things.
  • Nithya released 4th video on GenAI series in Tamil – Next word prediction using LSTM – see it here – https://www.youtube.com/watch?v=-f0QMUOdfOg
  • Tamil Open Source Conference 2025 is happening next month, in chennai. Check the details here – https://TossConf25.kaniyam.com

    Call for speakers is here – https://forums.tamillinuxcommunity.org/t/tossconf25-call-for-speakers/2913
  • On Saturday’s Tamil Grammar meetings, we are working on writing python code for tamil grammar rules using the very old book Tolkappiyam. Join and contribute, if you like to help for tamil language.
  • On Sundays, we meet at Kanchi Linux Users Group online meetings and discuss various open source things. We mentor students and job seekers to do some projects. Dont miss these meetings, to dive into older and modern technologies.
  • All our events are listed in the calendar at https://kaniyam.com/events subscribe to the google calendar there using computer. Thanks to Vanaja for curating all the events and publishing there.
  • Syed Jafer from parottasalna.com is one of the passionate FOSS contributor. He is a good trainer on Python, redis, data structures, git etc. He started a forum to discuss tech things. Post your questions here – https://forums.parottasalna.com/ Happy to see many forums are being built. Contribute to the open forums, open websites and keep them active and alive.
  • Books completed – சமயங்களின் அரசியல் – தொ. பரமசிவன். , ஓம் ஷன்ரிக்கியோ – பா. ராகவன்
  • Currently reading – What the internet is doing to our brains – The Shallows – by Nicholas Carr
  • What are you doing interestingly? Write them on your blog as individual blogs or as weekly notes like this.

Java Methods

What is method?

  • Method is block of code or collection(group) of statement that perform a specific task.All method in java belong to a class.method similar to function and expose the behavior of objects.which only runs when it is called.
  • method must have return type weather void or return data like int , string...etc
  • Method Naming convention in java first letter should be lowercase verb and use camel case for multiple words.

Syntax

AccessModifer returntype methodName(Parameter List)
{
// method body 
}

Access Modifiers:-

=> public, private, protected, default – controls method access

Method overloading:

Same class same method name , different parameters
(compile-time polymorphism)

Method Overriding:-

Different class (extend(is an-relationship) )parent and child relationship and Redefining-parent method in child class( same method name and parameters)

Types of methods:

In java is contain predefined and custom method , those methods have static and non-static method, we will see the later predefined methods(Already defined in the Java class libraries(Built-method)) .

 Object (java.lang.Object)
                    ↑
             Your Custom Class

  • In java Object class have already told static method and non static method, that object class contain mostly non-static method that method public-ally accessible and static methods have private or package-private(default-both classes have same package not to be subclass). they are not accessible for normal java developers,most of them used Jvm internally.

Predefine Static methods:

Example:-

1.Math -> Math.pow(x, y) -> Power (x^y)
2.Arrays -> Arrays.sort(arr) -> Sorts an array
3.Collections -> Collections.sort(list) ->Sorts a list.

Redefine Non-Static methods:

1.String -> str.length() Returns string length
2.String -> str.toUpperCase() Converts to 3.uppercase -> Scanner scanner.nextInt() Reads an int from user input
4.ArrayList -> list.add(x) Adds element to list

  • Static method
  • Instance method
  • Construtor(special method)

Why use methods?

To reuse code: define the code once , and use it many times

without method

public class Test_Withoutmethod {

    public static void main(String[] args) {

        int a =5 , b=3;
        int sum = a+b;
        System.out.println("Sum: "+ sum);

        int x=10, y=2;
        int result =x*y;
        System.out.println("Sum: "+result);
    }

}

with method:


public class Test_withMethod {


    static  void  add(int a , int b)
    {
        int sum =a+b;
        System.out.println("Sum: "+ sum);
    }
public static int minFunction(int n1, int n2)
{
    int min;
//  System.out.println("Min value is : "+min); you can not initialize local variable  ,when printing came compile time error.

    if (n1>n2)
    {
        min =n2;
    System.out.println("Min:n2 is : "+min);
    return min;
    }
            else
            {   
    min=n1;
    System.out.println("Min:n1 is : "+min);
    return min;
            }
    }


    public static void main(String[] args) {

   add(5,3);// callmethod 
   add(10,2); // reuse method 
   minFunction(1,2);
    }

}

Method Defining and Calling with return types and void :-


// method  defining and  calling
public class Method_Example1 {

    public static void main(String[] args) {
  int total= add(210,210);
  System.out.println(" Return value example => Total: 210+210 = "+total);
  twlethMark(550);
    }

    //  method using to void example 
    public static void twlethMark(int mark)
    {
        if(mark>580)
        {
            System.out.println("Rank:A1");
        }
        else if (mark >=550)
        {
            System.out.println("Rank:A2");

        }
        else
        {
            System.out.println("Rank:A3");
        }

    }

    public static int add (int n1,int n2)
    {
        int total = n1+n2;

        return total;


    }

}


swapping values inside method:-

public class Method_SwappingValue {

public static void main(String[] args) {

    int a =30;
    int b =45;
    System.out.println("Before swapping, a =" +a+ " and b ="+b);
    swapValueinFunction(a,b);
    System.out.println("\n Now ,Before and After swapping values will be same here");
    System.out.println("After swapping, a = "+a + ", b = "+b);
}

public static void swapValueinFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = "+a + ", b = "+b);

int c =a;  // a(30) value moved to c (),now a (empty) is  empty
a= b;  // b(45) value moved  a, because a is empty, now a is 45
b=c;  // c(30)  value   moved  to b(empty) , now b is 30
System.out.println("After swapping(Inside), a = "+a + ", b = "+b);



}

}

Method&Calling_Passing_Parameters

public class Method_Passing_Parameters {

    static String letter = " open the letter\n \n"
            + "To Smantatha,\n"
            + "\n"
            + "You are my heartbeat 💓\n"
            + "My heart is not beeping... because you're not near to hear it.\n"
            + "Come close and make it beep again.\n"
            + "Make my heart lovable with your presence. ❤️\n"
            + "\n"
            + "Forever yours,\n"
            + "Prasanth 💌";

    public static void main(String[] args) {
     sendLetter("prasanth","Java Developer"); //passing string parameter
    }

 static void readLetter(String reader,String career,int age) {
        System.out.println(reader+" read the letter from prasanth:");
        System.out.println(reader + letter);
    }

static void sendLetter(String sender,String career) {

System.out.println(sender+" sent a letter to samantha");    
//System.out.println("Message: "+letter);
System.out.println();
readLetter("samantha","Actress",35);

    }

}

Example: method using to return value and void

public class JavaReturnandVoid{

    public static void main(String[] args) {
        int Balance =myAccountBalance(100);
System.out.println("Balance: "+Balance);
System.out.println("\n");
samInfo(25,55);
char [] data=samInfo(25,55,5.9);
System.out.println(data);


    }

static void samInfo(int i, int j) {

    System.out.println("Age: "+i);
    System.out.println("Weight: "+j);


    }

// differen  paremeter if you have ,  how to return  ?
static char[] samInfo(int i, int j, double d) {
    System.out.println("differen  paremeter if you have ?  how to return ");
    String data = "Age:" +i+", weight"+j+", Height:"+d;
    return data.toCharArray(); //convert to char[]

}

static int myAccountBalance(int AccountBalnce ) {

    int myPurse = 1;
    int Balance =myPurse+AccountBalnce;
        return Balance;
    }


}

<u>How to different way return the value:-</u>

public class MethodReturnExample {

public static void main(String[] args) {
    // 1. calling void method 
     greet();
     // 2. calling int return method
       int sum=add(210,210);
       System.out.println("sum: "+ sum);
       //3.calling  String return method
       String message=getMessage("Prasanth");
       System.out.println(message);
       //4. calling method that returns both and string
          Object[] data=getUserinfo();
          System.out.println("Id "+ data[0]);
          System.out.println("Name "+ data[1]);


}

// 1.void method - just print
static void greet() {
System.out.println("Hello ,Welcome to java ");
}
//2. return int

static int add(int num1,int num2)
{
int sum= num1+num2;
return sum;

}
//3. return string

static String getMessage(String name)
{
return "Hi My name is " + name +" i am Javadeveloper";
}

//4. return int and string using object[] or Array
static Object[] getUserinfo()
{
int id =101;
String name ="Hellow";
return new Object[] {id,name};
}

}



<u> Important Return Type Scenarios</u>

int return 5 + 3; Return a number
String return "Hello"; Return a message or text
boolean return a > b; Return true/false
char[] return name.toCharArray(); Return letters from a string
Array return new int[]{1,2,3}; Return multiple numbers
Object return new Person(...); Return class object
void System.out.println("Hi"); Just perform action, no return


// method ovlerloading and overriding we will see Java Oops concept


<u>Method&Block Scope:-</u>

public class MethodandBlock_Scope_Example {

public static void main(String[] args) {

//System.out.println(x);
int a =100;
System.out.println(a);
//method Scope: x is visible any where inside main method
//Anywhere in the method
int x =100;
System.out.println("x in method:"+x);

    if(x>50)
    {
        //Block Scope: y is only visible inside this if block
        //only inside the block
        int y =200;
        System.out.println("Y in if block: "+y);

    }
    // try to access y outside the block
//  System.out.println("y is outside if block: "+y); //error not visible out of block

    }

}



<u>Java Recursion:-</u>



package java_Method;

// Factorial Using Recursion
public class Recursion_Example {

int fact(int n)
{
    int result;

    if (n==1)

        return 1;
        result =fact(n-1) * n;

        /*fact(3-1) *3 -> fact (2) * 3  becomes -> (fact(1) *2)*3)
         * fact(4-1) *4 -> fact (3) * 3  
         * 
         * 
         * 
         * 
         */
        return result ;


}


public static void main(String[] args) {

    Recursion_Example obj1 = new Recursion_Example();
    System.out.println("Factorial of 3 is "+ obj1.fact(3));
    System.out.println("Factorial of 4 is "+ obj1.fact(4));
    System.out.println("Factorial of 5 is "+ obj1.fact(5));
  • fact(5) = 5 x 4 x 3 x 2 x 1 =120
  • fact(1) = 1
  • fact(2) =1*2 =3
  • fact(3) =2*3 =6
  • fact(4) =6*4 = 24
  • fact(5) =24*5 =120
  • ------------------
  • fact(4) = 4 × 3 × 2 × 1 = 24
  • fact(1) =1
  • fact(2) =1*2 =3
  • fact(3) =2*3 =6
  • fact(4) =6*4 =24
  • fact(4) =24
  • ------------------
  • fact(3) = 3 × 2 × 1 = 6
  • fact(1) =1
  • fact(2) =1*2 =2
  • fact(3) =2*3 =6
  • ------------
  • *

    }

}


// Sum of Natural Numbers Using Recursion
public class RecursionExample1 {

public static void main(String[] args) {


    int result = sum(10);
    System.out.println(result);


}

public static int sum(int k)
{
    if(k>0)
    {
        return k+ sum(k-1);
    }

    else
    {
        return 0;
    }
}

}






<u>Feature of Static Method:-</u>

- A static Method  in java manage to the class, not with object (or) instance.
- It can be accessed by all instance  of in  the class, but it does not relay on specific instance.
- static method can accessed directly  static variable without need to create object ,you can access directly. but can not  access non-static member  directly you need to create to object. 

- you can call static method directly another static method and non-static method.

<u>Features of Non-static Method:-</u>

-  In an instance method, you can access both instance and static members (field(use) and methods(calling) directly, without creating an object.
-static variable can not declare to instance and non-static method is useless , you can use only class level not inside of methods. 


Types of instance Method:-
1.Accessor Method (Getters)

Used to read/access the value of a private instance variable, start with the  get.

public class Person {
private String name; /private variable

//Accessor method (getter)
public String getName()
{
return name;
}



2.Mutator methods (Setters)

used to update/modify  the value of private instance variable.Also supports encapsulation.start with set.

public class person
private String name;

//Mutator method (setter)
public void setName(String name)
{
this.name =name;
}
{
this.name = name;
}




Constructor

What is constructor?

  • A constructor is a special type of method it used to initialize objects.

  • It has same name as the class and does not have a return type.(why do not return type because constructor is initialize the object .not to return value).

  • Called automatically when an object is created using new keyword.

Constructor:-

  • Java constructor is special type of method that are used to initialize object when it is created
  • It has the same name as its class and is syntactically similar to a method ,however constructors have no explicit return type include void .
  • You will use a constructor to give initial values to the instance variables defined by the class or to perform any other star-up procedures required to create a fully formed object.

  • All classes have constructor , whether you define one or not because java automatically provides a default constructor that initializes all member variables to zero.once you define your constructor , the default constructor is no longer used.

  • Constructors in Java are called automatically when you create an object to initialize objects attributes(instance variable 0r data).

  • Constructors in Java are used only to initialize instance variables, not static variables(just try to static variable for initialize ,no came error but not recommend ). Each object get its own copy of the variables,they are stored in different memory locations.you can have only one constructor with the same parameter list(signature)
    ,you can create many objects using that constructor.

Why Constructors Can’t Be Inherited?

Constructors are not inherited: Sub-classes don't get super class constructors by default. or You cannot inherit (or override) a constructor from a parent class in a child class.But you can call the constructor of the parent class using super().

What does “inherited” really mean?
when a child class gets access to the parent class's and variables automatically-without writing again in the child class

Note: just they are inherited , does not automatically called (You get access automatically, but you use them manually), you still need call them like any normal method or variables.

when a child class extends a parent class ,it inherits method and variables , but not constructors.
The child class must to explicitly call the parts's constructor using super();

Example:-

public class Parent_Child {

    String var="Parent_variable";
Parent_Child
{
        System.out.println("Parent Constructor");
}

    void show()
    {
        System.out.println("Parent_instacemethod");
    }

}


public class Child_parent  extends Parent_Child{

Child_parent {
        super(); //  You must call it, not inherited
        System.out.println("Child Constructor");
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
    //    // Child class doesn't define 'var' or 'show()' but it gets them from Parent  
        Child_parent obj1 = new Child_parent();
        obj1.show(); // You’re calling the inherited method
        System.out.println(obj1.var); // You’re accessing the inherited variable.


    }

}

Constructor cannot be overridden

Overriding means redefining a method in a child class with the same signature.
But constructor are not inherited , so you can not override them.Also constructor are not normal methods, so overriding does not apply.
finally constructor can not to be inherited and overriding .

class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}

class Child extends Parent {
    // This is not overriding
    Child() {
        System.out.println("Child Constructor");
    }
}

Rules for creating java Constructor:-

  • The name of the constructor must be the same as the class name.
  • Java constructors do not have a return type include void.
  • In a class can be multiple constructors in the same class ,this concept is known as constructor overloading.
  • You can use the access modifier in the constructor ,if you want to change the visibility/accessibility of constructors.
  • Java provides a default constructor that is invoked during the time of object creation . if you create any type of constructor, the default constructor (provide by java) is not invoked(called).

Cannot be called like normal methods (c.Parent() calls the method, not constructor)

do not define two constructor with same parameter type even if parameter names are different ,java can not accept.

Example:

class Student {
Student() {
System.out.println("Constructor called!");
}
}

public class Test {
public static void main(String[] args) {
Student s = new Student(); // Constructor is called automatically here
}
}

output:-
Constructor called!

You do not call the constructor like a method (s.Student()).
You just create the object, and Java will automatically call the constructor.

Creating constructor:-

Syntax

Class ClassName{



Classname()
{
}
}

Types of Java Constructors:-

  • Default constructor(implicit Default constructor) => No parameters and invisible.
  • No-args Constructor.(explicit Default constructor) => No parameters
  • Parameterized Constructor => with parameters multiple constructor with different parameters.Used to initialize object with specific values.

Default constructor

If you do not create any constructor in the class, java provides a default constructor that initializes the variables to default values like 0,null,false.

public class DefaultConstructor {
    String name ;
    int age;
    String jobRole;
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        DefaultConstructor obj1 = new DefaultConstructor();
        obj1.name="R.prasanth";
        obj1.age=25;
        obj1.jobRole="JavaDeveloper";
        System.out.println("Name: "+obj1.name+", Age: "+obj1.age+", JobRole: "+obj1.jobRole);

    }
}

Example:2

public class DefaultConstructor1 {
    int id;
    String name;
    public static void main(String[] args) {

        DefaultConstructor1 s1 =new DefaultConstructor1();
        System.out.println("ID: "+s1.id);
        System.out.println("Name: "+s1.name);

    }
}

No-args Constructor.

The No-Argument constructor does not accept any argument,By using the no-args constructor you can initialize the class data members(fields or global variable) and perform various activities that you want on object creation.

Example:-


public class SimpleConstructor {
    //Explicitly you created constructor now ,no more invoked java provide default constructor
    SimpleConstructor()
    {
        System.out.println("Vankam da mapla Thiruttani irunthu");
    }
    public static void main(String[] args) {
        System.out.println("The main() method ");
        //creating a class's object, that will invoke the constructor.
        SimpleConstructor obj1 = new  SimpleConstructor();

    }
}


Example;1

public class NoArgsConstructor {
    int id;
    String name;

    NoArgsConstructor()
    {
        id =101;
        name ="Jhon";

    }

    void show ()
    {
        System.out.println("ID: "+id+", Name: "+name);
    }
    public static void main(String[] args) {
        System.out.println("NoArgs-constructor");

        NoArgsConstructor s1 = new NoArgsConstructor();
        s1.show();
    }
}

3. Parameterized Constructor

A constructor with one or more arguments is called a parameterized constructor.
use when you need to initialize different objects with different data.
Use with this keyword to avoid confusion between parameter and instance variable

Example:1

public  class Parmet_Constructor {

    String name,jobStatus,jobFinding;
    static int age;

    Parmet_Constructor (String name,int age,String jobStatus,String jobFinding)
    { //this.varName → refers to current object's variable.
     this.name=name;
     this.age=age;
     this.jobStatus=jobStatus;
     this.jobFinding=jobFinding;
    }
    public void  studentDetails()
    {
        System.out.println("name: "+ name+", age: "+age+",jobStatus: "+jobStatus+",jobfinding: "+jobFinding);
    }

    public static void main(String[] args) {
        Parmet_Constructor  obj1 = new Parmet_Constructor ("Prasanth",25,"Job_seeker","Java_Developer");
        obj1.studentDetails();
    }
}


Example:2

public class ParameterizedConstructor {
   int experience ; 
   int salary;
   String jobVacancy, name;
   // Parameterized constructor
   ParameterizedConstructor(String name, String jobVacancy, int salary,int experience) {
       this.name = name;
       this.jobVacancy = jobVacancy;
       this.salary = salary;
       this.experience= experience;
   }
   void candidateInfo() {
       System.out.println("Candidate Name: " + name);
       System.out.println("Job Vacancy: " + jobVacancy);
       System.out.println("Salary: " + salary);
       System.out.println("Experience: " + experience);
       System.out.println("-------------------------------");
   }
   public static void main(String[] args) {
       ParameterizedConstructor candidate1 = new ParameterizedConstructor("Prasanth", "Java Developer", 25000,1);
       ParameterizedConstructor candidate2 = new ParameterizedConstructor("Vignesh", "Frontend Developer", 26000,1);
       candidate1.candidateInfo();
       candidate2.candidateInfo();
   }
}

Constructor Overloading:-

Constructor overloading means multiple constructors in a class.when you have multiple constructor with different parameters listed, then it will be known as constructor overloading.

Example:

/constructor overloading
public class StudentData_ConstructorOverloading {
    //fields or globalvariable
   String name, gender, class_section, DOB, BloodGroup;
   float height;
   int id;
   // Constructor 1
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section, String BloodGroup) {
//this used to refer to current object's variable:
       this.id = id; //local variable opposite side global variable
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
       this.BloodGroup = BloodGroup;
   }
   // Constructor 2
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section, String DOB, float height) {
       this.id = id;
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
       this.DOB = DOB;
       this.height = height;
   }
   // Constructor 3
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section) {
       this.id = id;
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
   }
   void studentData() {
       System.out.println("ID: " + id);
       System.out.println("Name: " + name);
       System.out.println("Gender: " + gender);
       System.out.println("Class Section: " + class_section);
       System.out.println("DOB: " + DOB);
       System.out.println("Blood Group: " + BloodGroup);
       System.out.println("Height: " + height);
       System.out.println("-----------------------------");
   }
   public static void main(String[] args) {
       StudentData_ConstructorOverloading student1 = new StudentData_ConstructorOverloading(1, "Mukesh", "Male", "A", "B+");
       StudentData_ConstructorOverloading student2 = new StudentData_ConstructorOverloading(2, "Prasanth", "Male", "C", "03/06/2000", 5.10f);
       StudentData_ConstructorOverloading student3 = new StudentData_ConstructorOverloading(3, "Shivan", "Male", "B");
       student1.studentData();
       student2.studentData();
       student3.studentData();
   }
}
// global/field(static/non-static)  if do not initialize variable value it will provide default value.
/*
* int byte shrot long-> 0
* float double -. 0.0
* String  null
* boolean  default value is false
* 
*
*
*/


Example:-

public class Student_Constructor_DoandDonot {

    int id;
    String name,department;
    char gender;

    Student_Constructor_DoandDonot(int id, String name,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
    // do not define  two constructor with  same  parameter type even if parameter names are different ,java can not accept
    /*
    Student_Constructor_DoandDonot(int id, String name,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
*/
    /*
    Student_Constructor_DoandDonot(int Id, String Name,String Department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
    */
    Student_Constructor_DoandDonot(int id, String name,char gender,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
        this.gender=gender;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    //do's
        Student_Constructor_DoandDonot student1 =new Student_Constructor_DoandDonot(101,"Prasanth","ComputerScience");
        Student_Constructor_DoandDonot student2 =new Student_Constructor_DoandDonot(102,"shivan","History");
        Student_Constructor_DoandDonot student3 =new Student_Constructor_DoandDonot(103,"Parvathi",'F',"History");
        student1.infoStudent();
        student2.infoStudent();
        student3.infoStudent3();

    }
    public void infoStudent() {
   System.out.println("id: "+id+", Name: "+name+", Department:" +department);       
    }
    public void infoStudent3() {
        System.out.println("id: "+id+", Name: "+name+", Gender:"+gender+", Department:" +department);       
        }
}

  • Constructors cannot be inherited, but you can call superclass constructor using super().
  • You cannot inherit (or override) a constructor from a parent class in a child class.
  • Constructors can use this keyword to refer to the current object.

=>this()

  • This refers current class object
  • This used to call another constructor in same class
  • this() Only use to inside constructor not any others
  • Must be the first line in the constructor.
  • not allowed in normal methods.
  • Does not work with static methods or variables.
  • can not be used with super() in same constructor. helps when may constructor share common values.
  • To access current class instance variable (to avoid confusion with parameter name)
  • To call instance method of same class

What this does not do:

  • Not for inheritance
  • Not for typecasting
  • Not used for calling parent constructor (use super() for that

=>super()

  • Used to call parent class constructor.
  • you can use super() inside the first line of the child class constructor to call parent constructor. (when you create a child object, the parent part must to initialized first , because the child inherits from the parent,so parent constructor must be called before the child constructor runs).

why to initialize parent class fields? (or)
Used to initialize parent class properties.
In child classes to call parent constructor (especially if the parent class has a parameterized constructor). you access instance variable and can call parents instance methods and constructor using super().

  • Every child constructor must call a parent constructor (either explicitly with super() for parametrized constructor or implicitly (java automatically call ) if parent has no-args constructor). otherwise compilation error. why? Because java needs to create the parent part of the object first.even if yo did not write extends your class still extends object class,this class parent of all custom class in java.

if the parent only has parameterized constructors, you must explicitly call super(args) in the child constructor.if the parent has no-args constructor, and do not write super(), java add it automatically.

To access parent class variables/methods (if child class has same name).You cannot inherit constructors – Only call them using super()
Why?
A constructor name = class name, so it’s always specific to its own class.

Explain constructor overloading with example?

Constructor overloading means creating multiple constructor with the same class name but different parameter(number,type,order),purpose to initialize objects different ways.

What happens if both this() and super() are used?

you can not use both this() and super() in the same constructor, because both must be the first statement in the constructor.

Why constructors can’t be inherited?
comment me in the blog.
hint: inheritance is allows a child class it inherit properties(fields) and behavior(method) from parent class.

How do this and super differ?

Image description

When is constructor called in real life?

Constructors are automatically called when an object is created using new keyword.
Real-time Use Cases:

When reading user data (like name, age) into an object.

When fetching data from a database and storing in object (e.g., Employee, Product).

While creating objects in Java applications, games, or backed APIs.

can we create object in instance method?
yes we can create object in instance method.

Allowed Modifiers/Keywords for Constructors

Allowed

1.public - unrestricted Access
2.protected - subclass(is-relationship(extends)+ same package access.
3.default(package-private) - only accessible within the same package.
4.private - only usable within the class,
not Allowed (use-case Singletons & factory methods)

Not Allowed

5.final - constructors are implicitly final
why constructor are not inherited or overridden
6.static - constructor are always instance-related(used to initialize objects). static keyword use for constructor useless, static is class specific .

  1. abstract - abstract class can not create it's object directly,if you have abstract method must to be implemented child class.that's why does not work with constructors. simply:- abstract means:
  2. No implementation (no body).
  3. Child classes must provide the logic. 8.Synchronized

Constructor Programme:

this() using constructor:

super() using construtor:-

package inheritence;

public class Vehicle {
int speed;


 Vehicle(int speed)
 {
     this.speed=speed;
     System.out.println("Vehicle constructor: speed set to "+speed);


    }

}

package inheritence;

public class Car extends Vehicle{
    String model;
    Car (int speed,String model)
    {
        super(speed);
        this.model=model;
        System.out.println("Car constructor: model set to " + model);
    }

    void display()
    {
        System.out.println("Car speed: " + speed + ", Model: " + model);
    }

    public static void main(String[] args) {

        Car c1 = new Car(100,"Honda");
        c1.display();
    }

}

output:-
Vehicle constructor: speed set to 100
Car constructor: model set to Honda
Car speed: 100, Model: Honda

this() Example Program


public class Student {

    int id; 
    String name;

    Student()
    {
        this(101,"Default");
        System.out.println("No-arg constructor");
    }
    Student(int id,String name)
    {
        this.id=id;
        this.name=name;

  System.out.println("Parameterized constructor");
    }

    void infoDisplay()
    {
        System.out.println(this.id + " " + this.name); 
    }

    public static void main(String[] args) {

        Student student = new Student();
        student.infoDisplay();
    }

}

Constructor vs Method

Image description

copy constructor:-

A copy constructor is a constructor that creates new object by copying another object of the same class.

java does not provide default copy constructor you can create manually.

why to use copy constructor?
To create a duplicate(copy) of exiting object with the same values (copy data from one object to another).

what is clone() method?

It is method in java built in object class
it creates a copy(duplicate) of the object.

Example:-

Myclass obj1 = new Myclass();
Myclass obj1 =  (Myclass) obj1.clone();

clone () is complex to use correctly and it needs to implements cloneable and can cause errors.
recommended is copy constructor.

Important:-

what is mutable and immutable in java?

Mutable:
can be changed after the object is created.
If you class contains:
mutable fields( like arrays.lists,String Builder)
copy constructor must create new copies of those fields. This is called a deep copy. it each object independent data.No shared references.

Immutable:-
can not be changed once the object is created.

If you class contains:
Immutable fields Like String,Integer,Double,Boolean..etc
safe to just copy reference , no need to clone. This is called a shallow copy.

Example:


public class Example_Mutable_Immutable {




    public static void main(String[] args)
    {
        String s1 ="Java";
        String s2=s1 ;
        s1=s1+ "Programming";
        System.out.println("Immutable");
        System.out.println("s1 = "+s1);
        System.out.println("s2 = "+s2);
        StringBuilder sb1 = new StringBuilder("java");
        StringBuilder sb2= sb1;
        sb1.append("Programming");
        System.out.println("\nMutable:");
        System.out.println("sb1 = " + sb1);
        System.out.println("sb2 = " + sb2);

    }

}

Output:
Immutable
s1 = JavaProgramming
s2 = Java

Mutable:
sb1 = javaProgramming
sb2 = javaProgramming

static and non static

static and non static

static

  • static is class specific
  • static variable: only one copy of it exists, and all objects share that one copy.

  • static method: Can be called using the class name directly, doesn't need an object.

what can be static java?
1.varibles(fields)
class Student{
static String college = "Jaya College";
}

  1. static methods(class-level method)

used when:

  • you don't need to use object data(this)

- you want to call it without creating an object.

`class Utility
{
static void printMessage()
{
System.out.println("hell from static method");

}
}

//calling using Utility.printMessage();
`
3.Static Blocks(Runs only once when class is loaded)
used to : initialize static variable


class Example
{
static int data;
static {
data =100;
System.out.println("Static block executed");
}
}

4.static Nested class

use when : you want a class inside another class without needing the outer class object.

`
class Outer {
static class Inner {
void show() {
System.out.println("Inside static nested class");
}
}
}

`
call using:

Outer.Inner obj = new Outer.Inner();
obj.show();

you cannot use static :

Local varibales (int x=5; inside a method) static
Constructor static
Classes (top-level) static ( unless they are nested inside another class)

Example

class car {
static int car =4;
}
// now whether you create 1 object or 100 , all cars shares the same number of weels 

//static = belongs to class, shared by all, only one copy.



public class MyClass2 {
      static int val =1;
    public static void main(String[] args) {


        MyClass2 obj1 = new  MyClass2();
        MyClass2 obj2  = new  MyClass2();

        obj1.val=10;
        System.out.println("obj1 val:"+obj1.val);
        System.out.println("obj2 val:"+obj2.val);


    }

}

output:
obj1 val:10
obj2 val:10
//

non static

  • non-static is instance specific
  • if a variable is non-static ,then every object has its own separate copy that mean Non-static members belong to the object, it gets own copy of non static variables and can use non-static method.
Example: 1

public class MyClass {
    int val =1;

    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();

        obj1.val=10; // change  value for obj1

        System.out.println("obj1 val:"+obj1.val);
        System.out.println("obj2 val:"+obj2.val);

    // non-static = belongs to object, each object has its own value.   



    }

}

output:
obj1 val:10
obj2 val:1

  1. non-static variables (instance variable)

use when: Each object should have it own values.

example 2:

class Student 
String name;
int id;

Student (String name ,int id)

{
this.name =name;
this.id = id;

}


void display()
{
System.out.println(name +"  "+id);
}




public  class Test {

public static void main(String[] args)
{
Student s1 = new Student("John", 1);
Student s2 = new Student("Emma", 2);
s1.display(); //John
s2.display(); //Emma
}

}

  1. Non-static Method (Instance Method) used when you want to work with object data like name,id you need use this keyword
class Car {
    String brand;

    void showBrand() {  // non-static method
        System.out.println("Brand: " + brand);
    }
}

//you must to create object to call it:

public class Test {
public static void main(String[] args)
{
Car c = new Car();
c.brand="Tata";
c.showBrand();
}
}

  • you can not use non-static members inside static methods directly.
class Example {
    int x = 10;  // non-static

    static void show() {
        // System.out.println(x); // Error
    }
}

//To access x, you must create an object:
static  void show {
Example e shwo = new Example();
System.out.println(e.x);
}

Image description

Image description

What does “belong to class” mean?

  • It means the variable or method is shared by all objects of that class.
  • You don’t need to create an object to access it.
  • Use the static keyword.

What does “belong to object” mean?

  • It means each object has its own copy of that variable or method.
  • You need to create an object to use it.
  • Do not use static keyword.

why can not use to static in class(top-level)?

because not belong to any another class, only for static variable ,block,methods ,inner class

now see top level-class valid and invalid modifiers for class

Valid Modifiers for Top-Level Classes:

1.public -> class is accessible from anywhere
2.default -> no keyword=package-private, used only within the same package.
3.abstract -> class cannot-be instantiated(can not create object) ,must be inherited(extend) and If the subclass does NOT implement all abstract methods,
then the subclass must also be declared abstract. Abstract class can have normal methods too.
// we will detail info of abstraction concept

Why can't we create an object of an abstract class?

Abstract class is incomplete- it might have abstract methods(with out body). you must create a subclass that completes those methods. so that's why doesn't allow you to create object directly.

Why abstract class cannot achieve 100% abstraction?
Because:

  • An abstract class can contain concrete methods (with body).
  • So, not everything is hidden from the user.
  • That’s why it cannot achieve 100% abstraction. You can say: Abstract class = Partial abstraction

Why interface can achieve 100% abstraction?

Because:

  • All methods in an interface are abstract by default (before Java 8).
  • You cannot write method body (in older versions).
  • It only contains method declarations, no implementations. So, the user only sees "what to do", not "how".
Animal a = new Animal();  // Error: Cannot instantiate abstract class
Animal a = new Dog();  //  Allowed: Dog is a subclass of Animal/

4.final -> class cannot be extended( no sub classing) like not is-relationship or prevent inheritance

Invalid Modifiers for Top-Level Classes:

1.private -> No class can see it in the world, so it's useless.
2.protected -> used for members only (variable and methods), not for top-level class
3.static -> Only for inner class, not outer class.

how and where static, instance, and local variables and methods are called, accessed, and hold values.

class Variable {

int instancevar=10;
static int staticVar =20;

    public static void main(String[] args) {
//local variable must be initialized        
    int localVar=30;
    System.out.println("Local variable"+localVar);
    System.out.println("Static Varibale:"+staticVar);
    //accessing instace variable -> directely not allowed 
    //System.out.println("Instace variable:"+obj1.instancevar);

    Variable obj1= new Variable();
    System.out.println("Instace variable:"+obj1.instancevar);
    obj1.instanceMethod();




}
 static void staticMethod()
    {
        System.out.println("inside static method");
        System.out.println("Static Varibale:"+staticVar);
        Variable obj1= new Variable();

        System.out.println("Instace variable:"+obj1.instancevar);
    }
 void instanceMethod()
    {
        System.out.println("inside instace method");

        staticMethod();
        System.out.println("Static Varibale:"+staticVar);
        System.out.println("Instace variable:"+instancevar);

    }
}

Note:-

  • Static Method: Can only access static members directly.
    • To access instance members, create an object.
  • Instance Method: Can access both static and instance members directly.
  • Local Variables: Only exist inside the method, and must be initialized.

Example:-

public class StaticandNonStatic_Example {


    static int staticCounter =0;

    int instanceCounter = 0 ;

    //static method
    public static void staticMethod()
    {
        System.out.println("Inside static method");

        // Access static variable directely 
        System.out.println("static Counter:"+ staticCounter);

        // can not access non-static variable directely
        //System.out.println(instanceCounter);//error
        // can not call non-static method directely

    //  instanceMethod(); //error
    }

    // non-static  method
    public void instanceMethod()
    {
        System.out.println("Inside Non-static(instance) method");
// 
        System.out.println("Static counter: "+staticCounter);
        System.out.println("Instance Counter:  "+instanceCounter);
        staticMethod();
    }
    public static void main(String[] args) {
        //  

        StaticandNonStatic_Example obj1 = new StaticandNonStatic_Example();

        StaticandNonStatic_Example obj2 = new StaticandNonStatic_Example();
        obj1.instanceMethod();
        System.out.println("inside of staticMethod in non-staticCounter "+obj1.instanceCounter);
         obj1.instanceCounter =1;
         System.out.println("Reassigning value instanceCounter in static method:-  "+obj1.instanceCounter);

        //System.out.println("Inside of Staticounter"+staticCounter);

    }


}


❌