Templates by BIGtheme NET

Java As programming language

In this Article, I will explain basics of Java including,
How to do Programming thinking about java. fundamentals includes Class,
Object, abstraction, inheritance and polymorphous. Conditional and
Equality operators in Java. How to work with for loops (Kinds of for loops with examples)
in different java version 1.4, 1.5…1.8 (latest). How to work with simple arrays and strings.

Programming thinking about java :

Before object oriented languages like Java.
There are different procedural oriented languages in market.

Then, What is Procedural programming?
In procedural programming our code is organised into small “procedures” that use
and change our data.

procedural

What are the limitations of Procedural programming?

1) Code extending is not easy.
2) Takes more development time and effort.
3) Supported utils and libraries are very limited.
4) We can develop robust applications.

There are many limitations with programming languages. Then start thinking about Object oriented languages.

What is Object oriented programming?
In object oriented programming, the data and related functions are bundled together into an “object”.

oob

2) Java fundamentals :
There are many java fundamentals, As a java programmer, You should know given four features.

1) Class and Object :

Object is the physical as well as logical entity whereas class is
the logical entity only.

Object in java :

An entity that has state and behavior is known as an object.
Examples are, chair, bike, marker, pen, table, car etc.

Objects

State: Represents data (value) of an object.

Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.

Identity: Object identity is typically implemented via a unique ID.

The value of the ID is not visible to the external user. But,it is used internally by the JVM(Java Virtual machine)
to identify each object uniquely.

For example: Pen is an object. Its name is Reynolds, color is white etc. known as its state.
It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.

What is a Class :

A class is a group of objects that has common properties.
It is a template or blueprint from which objects are created.

A Class is a model, that does not holds any memory.
A class in java can contain: data member, method, constructor, block, class and interface.

Syntax is,

class class_name{
        data members;
        member functions/ methods.
}

Class

Member variables are simple variables, Syntax to declare member variables.

Bank.java

package com.devjavasource;

public class Bank {

	// Member Variables
	int bankId;
	String bankAddress;
	String bankName;
		
	// Member Functions/ Methods
	public static void main(String[] args) {
		// Create and object for Bank
		Bank bankObj = new Bank();
		
		System.out.println("Bank Id is: " + bankObj.bankId);
		System.out.println("Bank Address is: " + bankObj.bankAddress);
		System.out.println("Bank Name is: " + bankObj.bankName);
	}
}

Classsss

2) Abstraction :

Abstraction is a process of hiding the implementation details
and showing only functionality to the user.

Suppose, Some third party software are using some of our features.
In that case, we just provide some API methods to call our actual features.
So that, we can hide How these features are implemented from third party vendors.

3) Inheritance :

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Syntax of Java Inheritance,

class Subclass-name extends Superclass-name  
{  
   //methods and fields  
} 

The extends key word indicating that your are extending a super class.

4) Polymorphous :

This is How we can perform single action by different ways.

Animal is a Super class, Dog and Horse are the sub-classes of animal class.

Animal is having eat() method. This has general implementation of How Animal eat.

But, In case of Dog, this eat method should be override with How Dog eat.
In case of Horse, this eat method should be override with How Horse eat.

polymarphism

Animal.java

package com.devjavasource;

public class Animal
{
	void eat(){ 
		System.out.println("Code that implements, How Animal eat.....");
	}
}

Dog.java

package com.devjavasource;

public class Dog extends Animal
{
	void eat(){ 
		System.out.println("Code that implements, How Dog eat.....");
	}
}

Horse.java

package com.devjavasource;

public class Horse extends Animal
{
	void eat(){ 
		System.out.println("Code that implements, How Horse eat.....");
	}
}

InheritanceAndPolyTest.java

package com.devjavasource;

public class InheritanceAndPolyTest {

	public static void main(String[] args) {
		
		Animal animalObj = new Animal();		
		animalObj.eat();
		
		//Assign Dog object to animal reference
		animalObj = new Dog();
		animalObj.eat();
		
		// Assign Horse object to animal reference
		animalObj = new Horse();
		animalObj.eat();
	}
}

Select InheritanceAndPolyTest.java program and Run As -> Java Application.

Out Put :

Code that implements, How Animal eat.....
Code that implements, How Dog eat.....
Code that implements, How Horse eat.....

3) Conditional branching :

In Java, mainly two types of Operators.

(1) Conditional Operators and
(2) Equality check operators.

(1) Conditional Operators :
The operators available in java are,

(a) “and” operator (&&) – If both values are true, then result true. Otherwise false.

(b) “or” operator (||) – If any one of the value is true, then result true. Otherwise false.

(c) “not” operator (!) – Simply negate the value, If you supplied true then result will be
false and supplied false then result will be true.

(d) “question mark and colon” operator (? :) – this is conditional operator.
Syntax is, condition ? statement 1 : statement 2;

Here is the explanation, execute “statement 1” if the condition is true,
Other wise statement 2.

OperatorsInJava.java

package com.devjavasource;

public class OperatorsInJava {

	public static void main(String[] args) {

		boolean trueVal = true;
		boolean falseVal = false;
		System.out.println("********CONDITIONAL OPERATORS*************");
		System.out.println("And Operator test :" + (trueVal && falseVal));
		System.out.println("Or Operator test :" + (trueVal || falseVal));
		System.out.println("Not Operator test1 :" + !trueVal + " test2 :"
				+ !falseVal);

		System.out.println("******* Conditional Operator *****");
		System.out.println("Result is :"
				+ (trueVal ? getEmployeeDetails() : getOrganizationDetails()));
		System.out.println("Result is :"
				+ (falseVal ? getEmployeeDetails() : getOrganizationDetails()));

		int value1 = 1;
		int value2 = 2;
		System.out.println("\n********EQUALITY OPERATORS*************");
		if (value1 == value2)
			System.out.println("value1 == value2");
		if (value1 != value2)
			System.out.println("value1 != value2");
		if (value1 > value2)
			System.out.println("value1 > value2");
		if (value1 < value2)
			System.out.println("value1 < value2");
		if (value1 <= value2)
			System.out.println("value1 <= value2");

	}

	public static String getEmployeeDetails() {
		return "EMPLOYEE DETAILS METHOD CALL";
	}

	public static String getOrganizationDetails() {
		return "ORGANIZATION DETAILS METHOD CALL";
	}
}

Out Put :

********CONDITIONAL OPERATORS*************
And Operator test :false
Or Operator test :true
Not Operator test1 :false test2 :true
******* Conditional Operator *****
Result is :EMPLOYEE DETAILS METHOD CALL
Result is :ORGANIZATION DETAILS METHOD CALL

********EQUALITY OPERATORS*************
value1 != value2
value1 < value2
value1 <= value2

Conditions available in java are,

(a) Simple If condition.
Syntax is, if(condition) { // execute the code in if condition }

(b) If and else condition.
Syntax is,
if(condition)
{ // execute the code in if condition }
else{
// execute the else code
}

(c) switch condition.
Syntax is,
switch(variable)
{
case case1: code... to execute; break;
case case1: code... to execute; break;
case case1: code... to execute; break;
default: default case code....
}

4) for loops :
In java for loop is changing from version to version,

Before java 1.5, for loop is like a traditional for loop.

for(int loop variable; loop condition; loop variable increment/decrement)
{
        // Body of the for loop
}

In java 1.5, for loop is enhanced as advanced for loop.
Syntax is,

for(<> val : <>)
{
     // for loop body ....
}

Latest in java 1.8, foreach() is introduced to loop.
Syntax is,

anystreamObject.forEach(lambda expression);

Note that, lambda expression and stream are introduced in java 1.8.

If you are interested you can refer, streams in java-8-feature-streams
and lambda expressions in java-8-feature-lambda-expressions

ForloopsInJava.java

package com.devjavasource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ForloopsInJava {

	@SuppressWarnings("rawtypes")
	public static void main(String[] args) {

		// Traditional for loop, before 1.5 java version
		@SuppressWarnings("unchecked")
		List ls = new ArrayList(Arrays.asList(1,2,3,4,5,6));
		System.out.println("============Traditioal for loop====================");
		for(int cnt=0; cnt < ls.size(); cnt++)
		{
			System.out.println("value is: " + ls.get(cnt));
		}
		System.out.println("============Advanced for loop====================");
		// Advanced for loop java 1.5 version on wards.
		List lsAdvanced = new ArrayList<>(Arrays.asList("A","B","C","D","E","F"));
		for(String val : lsAdvanced){
			System.out.println("value is: " + val);
		}
		
		System.out.println("============forEach()====================");
		// forEach() to loop the collections. (java 1.8 feature)
		lsAdvanced.stream().forEach(each -> {
			System.out.println("value is: " + each );
        });
	}
}

Out Put :

============Traditioal for loop====================
value is: 1
value is: 2
value is: 3
value is: 4
value is: 5
value is: 6
============Advanced for loop====================
value is: A
value is: B
value is: C
value is: D
value is: E
value is: F
============forEach()====================
value is: A
value is: B
value is: C
value is: D
value is: E
value is: F

5) Arrays and Strings :

What is Array?

The main purpose of Arrays is to store Homogeneous elements and all these elements
are stored with index starts from 0 (zero).

Two types of Arrays,
1) Single Dimensional Arrays
2) Multi Dimensional Arrays

Syntax is,

DataType[] ArrayName; // Single Dimensional
DataType[][][]..[] ArrayName; // Multi Dimensional

What is a String?

String is java immutable class, holds sequence of characters.
What is immutable, means - object in memory never be deleted, even if we changes the value.

Suppose,
String strObj = new Sting("abc");

Concat new String "xyz" to string object, strObj.concat("xyz");

But the actual String object values never is changed.

ArraysAndString.java

package com.devjavasource;

public class ArraysAndString {
	
	public static void main(String[] args) {		
		
		System.out.println("**********Single Dimensional Arrays**********");
		//Single Dimensional Arrays
		int[] array1 = { 1,2,3,4,5,6 };		
		for(int each: array1)
		{
			System.out.println("value is: " + each);
		}
		
		System.out.println("**********Multi Dimensional Arrays**********");
		//Multi Dimensional Arrays
		int[][] bankArray = { {1,3},{3,4} };		
		for(int[] each: bankArray)
		{
			for( int innerEach : each )
				System.out.println("value is: " + innerEach);
		}
		
		System.out.println("**********String Exmaple**********");
		String strObj = new String("abc");
		strObj.concat("xyz");
		System.out.println("String value is :" + strObj);
		
		strObj.concat(new String("xyz"));
		System.out.println("String value is :" + strObj);
		
		System.out.println("String value is :" + strObj.concat("xyz"));			
	}
}

Out Put :

**********Single Dimensional Arrays**********
value is: 1
value is: 2
value is: 3
value is: 4
value is: 5
value is: 6
**********Multi Dimensional Arrays**********
value is: 1
value is: 3
value is: 3
value is: 4
**********String Exmaple**********
String value is :abc
String value is :abc
String value is :abcxyz

*** Venkat – Happy leaning ****