Wednesday, 5 February 2014

Creating Object

Syntax to create an Object
     ClassName objectName = new ClassName();

     Example
          Person personA = new Person();

          Here Person is the class name
          personA is the object created for the class Person.

    Once the class is defiined, you can create any number of objects to it.

               Person personB = new Person();
               Person personC = new Person();

How to access properties of an object
     java provides '.' opertor to access th properties of an object.
     Syntax:
          objectName.propertyName = value;

     Example
          personA.height = 6;
          personB.height = 5.5;

How to call the behaviors
     Just like how you are accessing properties, you can call the behaviours.
     Syntax
     objectName.behavior();

     Example
     personA.getHeight();
     personB.getHeight();

Complete Working Example of Person class
class Person{
 float height, weight;
 String color, country;
 
 float getHeight(){
  return height;
 }
 
 float getWeight(){
  return weight;
 }
 
 String getColor(){
  return color;
 }
 
 String getCountry(){
  return country;
 }
 
 public static void main(String args[]){
 
  /* Declaring two person objects */
  Person personA = new Person();
  Person personB = new Person();
  
  /* Setting properties for personA object */
  personA.height = 6;
  personA.weight = 75;
  personA.color = "White";
  personA.country = "India";
  
  /* Setting properties for personB object */
  personB.height = 5.5f;
  personB.weight = 76;
  personB.color = "Black";
  personB.country = "America";
  
  /* Calling the behaviors and printing the details of personA */
  System.out.println("PersonA Height is " + personA.getHeight());
  System.out.println("PersonA Weight is " + personA.getWeight());
  System.out.println("PersonA color is " + personA.getColor());
  System.out.println("PersonA country is " + personA.getCountry());
  System.out.println();
  
  /* Calling the behaviors and printing the details of personB */
  System.out.println("PersonB Height is " + personB.getHeight());
  System.out.println("PersonB Weight is " + personB.getWeight());
  System.out.println("PersonB color is " + personB.getColor());
  System.out.println("PersonB country is " + personB.getCountry());
 }
}
   
Output
PersonA Height is 6.0
PersonA Weight is 75.0
PersonA color is White
PersonA country is India

PersonB Height is 5.5
PersonB Weight is 76.0
PersonB color is Black
PersonB country is America
  





Class Declaration                                                 instance Variables                                                 Home
Programming Languages
ABAP
ABAP is a programming language for building SAP business applications. Most of the SAP business applications written in ABAP.... Read more>>
Batch Scripting
Batch is a scripting language provided by Windows operating system. You can execute batch commands in command prompt.Read more>>
C#
C# is a programming language that supports more than one programming paradigm. The basic syntax of C# is similar to that of C, C++ and Java.Read more>>
Go
Go is an open source language to build reliable software in efficient way. Now a days many applications are developed in Go language. Read more>>
Groovy
Apache Groovy is a Java-syntax-compatible object-oriented programming language for the Java platform. Read more>>
Haskell
Haskell is a pure functional programming language developed in late 1980s, it is named after Haskell Curry, was an American mathematician and logician. Read more>>
Java
The Java programming language platform provides a portable, interpreted, high-performance, simple, object-oriented programming language and supporting run-time environment. Read more>>
JavaScript
Javascript is a scripting language, used to validate html form data, before submitting to the server. Now a days javaScript is also used for server side development. Read more>>
Julia
Julia is a dynamic programming language (It is optionally typed language, Specifying the type is optional, user choice), used for scientific and numeric computing. Julia is available on Windows, Linux and Mac platforms. Read more>>
Kotlin
Kotlin is a high-level programming language runs on JVM. Kotlin compiles the sources code into java byte code and runs the application using jvm. You can use java and kotlin interchangeably, means you can call a kotlin function from Java and vice versa. Read more>>
PHP
Php is one of the popular language to create dynamic websites. One of the key advantage of php is, it can talk to backend infrastructure like databases, file systems etc., Read more>>
Prolog
Prolog is a declarative programming language. It is mainly developed for AI (Artificial intelligence) programming. Prolog application maintains number of rules and facts, and derive the solution using the specified rules and facts. Read more>>
Python
Python is open source and is available on Windows, Mac OS X, and Unix operating systems. You can download and work with python for free.Python is fun to experiment and easy to learn. Python provides interpreter that can be used interactively, which makes it easy to experiment with features of the language. Read more>>
R
R is a free software environment for statistical computing and graphics. It runs on variety of UNIX platforms, Windows and MacOS. Read more>>
Scala
Scala is a general-purpose programming language like Java. Scala was developed to solve the shortcomings of Java Programming language. Distributed computing frameworks like Apache Spark uses Scala widely. Read more>>
BI Tools
Apache Superset
Apache Superset is a web-based data exploration and visualization platform designed to make it easy for teams to analyze data and build interactive dashboards. Read more>>
Big Data
Apache Druid
Apache Druid is A high performance, real-time analytics database that delivers sub-second queries on streaming and batch data at scale and under load. Read more>>
Apache Pinot
Apache Pinot is a real-time Distributed OLAP database designed to answer questions instantly. It is used when companies need to analyze a lot of data very quickly. Read more>>
BigQuery
BigQuery is a fully managed, serverless, highly scalable, and cost-effective cloud data warehouse designed for business agility. Read more>>
NiFi
Before we start building data flows in Apache NiFi, it is important to understand a few fundamental concepts that are commonly used in the world of data engineering. Read more>>
Fronend Development
CSS
CSS (Cascading Style Sheets) is used to control its visual appearance, such as layout, colors, fonts, and spacing. Read more>>
HTML
HTML stands for HyperText Markup Language. It's the standard language used to create and design webpages. Think of HTML as the building blocks of a webpage, providing the basic structure. Read more>>
JavaScript
Javascript is a scripting language, used to validate html form data, before submitting to the server. Now a days javaScript is also used for server side development. Read more>>
React
React is an open-source front-end JavaScript library, maintained by Facebook, that allows developers to build dynamic and responsive user interfaces. Read more>>
Machine Learning and GenAI
Cube Semantic Model
Cube is a semantic layer and analytics platform that helps developers build consistent, scalable, and high-performance data applications...... Read more>>
GenAI
AI is a field of computer science where machines are programmed to mimic human behavior or intelligence. ..... Read more>>
Langchain4j
LangChain4j is a Java library that makes it easier to connect your applications with language services, such as those from OpenAI or Google.... Read more>>
Machine learning for Beginners
Machine learning is a way of teaching computers to learn on their own, just like how humans learn from experience. Instead of telling the computer exactly what to do step by step, we give it lots of examples and let it figure out patterns by itself. Read more>>
MCP
Model Context Protocol (MCP) is an open protocol that standardizes how LLM-based applications interact with external systems.... Read more>>
Ollama tutorial
Ollama is an open-source tool designed to simplify the process of running large language models (LLMs) locally on your own hardware..... Read more>>
Build Tools
Maven
Maven is a project management tool based on the notation of POM (Project Object Model). It is one of the powerful and efficient build tool for java projects (There are other tolls like gradle and ant). Read more>>
Caching
Redis
Redis is a advanced key-value cache and store. Keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs. Redis is written in ANSI C and works in most POSIX systems like Linux. Read more>>
CI/CD
Jenkins
Jenkins – an open source automation server which enables developers around the world to reliably build, test, and deploy their software. Read more>>
Nexus
Nexus is a repository manager. We can publish our artefacts to nexus, so they can be available for other developers. Read more>>
CommandLine Http Client
HTTPie
HTTPie is a command line http client. It has very good expressive and intuitive syntax Read more>>
Containerization
Docker
Docker is a container platform, using this you can securely build, share and run any application, anywhere. Read more>>
Databases
Apache Derby
Apache Derby is open source RDBMS (Relational database management system) completely written in Java and maintained by Apache. Read more>>
Cassandra
Apache Cassandra is an open source, distributed data storage system. Read more>>
MongoDB
MongoDB is a open source NoSQL database, written in C++. MongoDB is a cross platform document oriented database. Read more>>
PostgreSQL
PostgreSQL or Postgres is a ORDBMS (Object Relational Database Management System) and is developed by the PostgreSQL Global Development Group. Read more>>
SQL
MySQL works in client-server model. You can use mysql client to communicate with mysql server. You can communicate to mysql client using SQL (Structured Query Language). Read more>>
Esoteric Programming Languages
Brainfuck
Brainfuck is a programming language created by Urban Müller in 1993. Brainfuck comes under esolang (esoteric programming language) category. Read more>>
Frameworks
Jersey
Jersey to Perform REST CRUD Operations. Read more>>
Spring
Spring is one of the most widely used Java EE frameworks. I have written a lot on Spring and spring boot. Read more>>
Struts2
Struts2 is a framework to build MVC(Model-View-Controller) web applications. Read more>>
Gaming
Kaplay
Kaplay is a powerful and flexible gaming library designed to simplify game development. Whether you're building a simple 2D platformer or a complex strategy game, Kaplay provides essential tools and abstractions to streamline the process. Read more>>
Load Testing Tools
Apache Benchmark
Apache Benchmarking (ab) is a tool used to benchmark your web applications. Using ab, you can get an idea of how many requests per second your application is capable of serving. Read more>>
JMeter
Apache JMeter is an open-source load-testing tool. It is a desktop application for load testing and performance measurement. JMeter is primarily designed to perform load testing on web applications (Client-server model based applications). Read more>>
Monitoring and Alerting
Prometheus
In today’s world of cloud-native applications and microservices, monitoring your systems isn't optional, it's a necessity. But traditional monitoring tools were not designed for today’s dynamic and distributed environments..... Read more>>
Reverse Proxy
NGINX
NGINX is a Reverse Proxy Server. Reverse Proxy server is an application that sits in front of web servers and forwards client requests to the respective web serve Read more>>
Search Engines
ElasticSearch
Elastic search is a open-source distributed analytics search engine, built on top of Apache Lucene. Elastic search can run on your Hadoop cluster, and can handle petabytes of data. Read more>>
Security
HashiCorp Vault
HashiCorp Vault is a service to manage secrets. Based on the policies configured, Vault provide APIs to manage the secrets. Read more>>
Servers
Jetty
Jetty is a server, used to deploy web applications. Jetty provides HTTP server, HTTP client, and javax.servlet container. Read more>>
Versioning Control Systems
Git
Version control system keeps track of the changes happened on a file (or) set of files. Git is one of popular distributed versioning control system. Read more>>
Other Topics
ASN.1
ASN.1 stands for 'Abstract Syntax Notation.One', It is an interface description language used to define structured information that can be serialized and deserialized in cross-platform way. Read more>>
Documentation
Documentation tools like Markdown are covered here Read more>>
Hadoop
Hadoop is open-source software for reliable, scalable, distributed computing. Read more>>
OpenSSL
OpenSSL is a popular open source cryptography library. In this tutorial series, I am going to explain different openssl commands that will help you in real time. Read more>>
TableSaw
TableSaw tutorial Read more>>
XML
XML stands for Extensible markup language. It is a specification for storing information. Unlike HTML, XML don’t have predefined tags, User can create custom tags by following the rules of XML. Read more>>

Declaring a class

class in java declared with a keyword “class”

    Syntax
    class ClassName{
    }

   Example
    class Person{
    }

How to declare properties of a class
  Each property is represented by a variable.

class Person{
 float height, weight;
 String color, country;
}

Since height and weight are real type values, so these are declared as a float. Where as color and country are of type String. So these are declared as type string.

Note:
   We haven't discussed anything about strings, just note that string a group of characters.

How to define behaviors for a class
   Each behaviour in Java represented by a method.

   Method is a block of statements, with a name associated with it.
      Syntax:
         returnType methodName(parameters){

         }
      Example
         int sum(int a, int b){
            return (a+b);
         }

      here,
         returnType is int
         parameters are a, b.

return value must match with the return type of the method.
After adding the behaviors for the class Person, code changed like below
class Person{
 float height, weight;
 String color, country;

 float getHeight(){
  return height;
 }

 float getWeight(){
  return weight;
 }

 String getColor(){
  return color;
 }

 String getCountry(){
  return country;
 }
}



Classes & Objects                                                 Object Creation                                                 Home

Classes and Objects

Before, moving in depth details of Object oriented and java features, will discuss what an object and class is.

Objects and class in Real World scenario

Object
An Object is a real world entity. For example, book, cat, box, bus, keyboard, person, screen, cell phone etc., all are objects.

So How can we differentiate objects
1. Depend on their properties
2. Depend on their behaviors

Differentiating two objects based on their properties
Lets say, there are two persons A and B, we already discussed, each real time entity is an object. So these two persons are objects.

First lets try to find what are the possible properties for the person object

Possible properties for a person
height, weight, color, Education Qualification, country, address are all come under person properties.

Now by comparing these properties we can easily differentiate two persons.
Properties Person A Person B
Height 6ft 5.5ft
Weight 75Kg 60Kg
Color white Black
Country India America
As shown in the above table, both the persons has their own properties, So we can differentiate based on them.

Differentiating two objects based on their behavior
consider the same two persons A and B. will try to figure out possible behaviors for the person object

Possible behaviors are
walk, run, swim, eat, sleep, see, hear etc., Now by comparing these behaviors we can easily differentiate two persons. 
Behavior Person A Person B
Walk 10km/hr 12km/hr
run 20km/hr 18km/hr
sleep 8 Hrs/day 6Hrs/day

Class
In normal terms I call class as a category.

All persons come under Human category
cat, lion, Elephant come under Animals Category

So a class or category is a group of objects with similar properties and behaviors.

Objects and class in Programming Terminology

What Is an Object?
An object is a software bundle of related state and behavior. The main advantage of java is you can compare objects in Java with real world objects. So it is very easy to work with objects in Java

What Is a Class?
A class is a blueprint or prototype from which objects are created.

Documentation Comments                                                 Class Declaration                                                 Home

Documenting Comments in java source file : javadoc tool

The Javadoc tool parses the documentation comments in a set of Java source files and produces a corresponding set of HTML pages describing the public and protected classes, nested classes (but not anonymous inner classes), interfaces, constructors, methods, and fields.

You can run the java doc tool on packages and on individual source files

will see the javadoc tool on a simple program first, will see javadoc on packages in packages section.

Example:
public class CommentsEx{
 /**
 * Program Execution starts from here
 */
 public static void main(String args[]){
  int marks;
  marks = 70;
  System.out.println(marks);
 }
}
when you call javadoc CommentsEx, then javadoc generates the documentation for the file

See the below figure
javadoc produce the documentation in html like below
                           















Comments in Java                                                 Javadoc tags                                                 Home

Comments in java

Comments in java, makes the program more readable.

Suppose you written thousand lines of program, with out proper documentation, after some time, for the owner of the application also, it is very difficult to figure out what was written.

Comments solve this problem :
By using comments, you can document your code at the time of writing program. Comments won't affect your program execution. Comments simply document your code.

Java supports 3 types of comments

     Single line comment :
          Single line comments starts with //
          // It is a single line comment

     Multi Line comment
     Multi line comments are encoded in /* */
          /* I am a mulltiline comment */

     javadoc tool uses doc comments when preparing automatically generated documentation.

     /**
     * Java doc comments
     */

Example
/**
* Author : Krishna
* Date : 5th Feb 2014
*/
class CommentsEx{
 public static void main(String args[]){
  int marks; /* variable marks represents the marks
                  obtained by a student */
  marks = 70;
  System.out.println(marks); //printing to console
 }
}

Output
70

Some Notable points

1. Giving more comments also makes your program not readable, use whenever needed.

2. Use meaning full names to variables like noOfMonths. avgSalary etc., these reduce to comment them explicitly

3. Use meaning full names to methods like sortAscend, sortDescend, searchElement etc., these reduce to comment them explicitly


How to iterate over a two dimensional array in Java?                                                 Documentation Comments                                                 Home

Branching statement: continue

continue statement skips the current iteration of a for, while, do-while loops. Just like break, continue also has two forms.
    1. unlabelled continue
    2. labelled continue

Unlabelled continue
    Syntax
        continue;

Example: Count the number of odd values from 0 to 10
class ContinueEx{
 public static void main(String args[]){
  int counter = 0;
  
  for(int i=0; i < 11; i++){
   if(i % 2 == 0)
    continue;
   System.out.println(i);
   counter++;
  }
  
  System.out.println("Total number of odd numbers from 0 to 10 is " + counter);
 }
}
       
Output
1
3 
5
7
9  
Total number of odd numbers from 0 to 10 is 5 
       
Labelled continue
     Syntax
     continue labelName;

Example
class ContinueEx{
 public static void main(String args[]){
  int counter = 0;
  
  myLabel:
   for(int i=0; i < 11; i++){
    if( i < 10)
     continue myLabel;
    System.out.println(i);
   }
   
  System.out.println("I am out of the label");
 }
}

Output
10
I am out of the label

break statement                                                 arrays                                                 Home