Friday, November 17, 2017

JUnit Tests Basics and how to do unit testing in java





Junit is one of the most popular unit testing framework for java developer Junit has been important in Test driven Implementation.

Below are the Annotation which are available in Junit 4

@Test Identifies a method as a test method
@Before Executed before each test. It is used to prepare the test environment (e.g read input data , initialize the class)
@After Executed after each test. It is used to cleanup the test environment.It can also save menory by cleaning up expensive memory structures.
@BeforeClass Executed once, before the start of all the tests. Methods marked with this annotation need to be definedas static to work with Junit.
@AfterClass Executed once after all the tests have been finished. Methods annotated with this annotation need to be defined static to work with Junit.
@Ignore Marks that the test should be disabled.
@Test(expected =Exception.class) Fails if the method does throw the named exception.
@Test(timeout =10) Fails if the method takes longer than 100 milliseconds.


Below is the Program where we are using the JUnit testing Basics








Thanks for reading
Noeik

Thursday, November 16, 2017

Java Interview : Heap Sort Implementation using Array

Heap Sort is not that much popular in the sorting mechanism but the heap sort is the one which actually help you in most of the complex problem solution. as it is one of the most efficient sorting algorithm.


Lets see the java program of implementing heap sort using Array.




Time Complexity of the program is O(nlog(n))



I hope this will help you in understand the heap sort , Please let me know if you have any issue or leave us a comment.


Thanks for reading
Noeik


Saturday, November 11, 2017

Spring JDBC - Connect Spring application to database using JNDI (Mysql)

JNDI now a day is very popular as it provide the underline database connectivity directly to the application which providing any driver and connection string and all , everything has to be defined at application server level only the JNDI name is what matters to the spring application , it basically connect with database only by using the JNDI Name .

So how to connect with database using jndi



In this program we are trying to connect our spring application with Mysql database using Mysql JNDI which we are defining in tomcat server of the application.

Below is the tag we need to add in the tomcat context.xml.

<Resource name="jdbc/springlearning" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/springlearning?useSSL=false"/>


below is the program

The structure of the project will be like below








Hope this will help you in understanding the program

Thanks for the reading
Noeik

Friday, November 10, 2017

Program to remove correspond duplicate character and reverse the string

Reversing the string is quiet simple in java but to remove the duplicate character in string without using and inbuild function or utility we need to do some brain storming.

There are 2 ways we can solve the problem.
1) Using Build in functions and solve the problem (Ex. Use HashSet to Remove Duplicate and Use StringBuilder to reverse the String)

2) To Use the Core logic without using any inbuild functions , here we need to use some thinking.

Below is the problem without using any in build function or utility.


So

Input - aabbcc
Output should be  - abc
Input - abbcaa
Output - abca





The Time Complexity will be - O(n) 

There is a simple way as well where we will only use String Buffer / String Builder and call .reverse() function of it.


If you have any problem in understanding the program , Please leave us a commet , will have to help.


Thanks for reading
Noeik

Tuesday, November 7, 2017

Spring MVC - Program for Implementing Dispatcher Servlet and Web.xml using Java annotation configuration

Spring as we all know is very popular because of its MVC framework. So we have 2 ways to Implement the Spring MVC using dispatcher servlet by Xml or can be configure by Java Annotation.

Below is the Program of Implementing the Java Annotation for Dispatcher Servlet and Web.xml for Spring MVC.



The Project will be Dynamic Web Program (Maven Project) and the structure will be like below

The Program will be like below








Thanks for reading , If you have any issue in program , let us know by leave a comment , Happy to help you

Noeik

Monday, November 6, 2017

Spring JDBC - Program to connect Database using jdbcTemplate

Spring jdbc is very important as all the enterprise level application always use database and Spring JDBC comes in picture when we connect database with java application using spring framework.


Below  program we are using the spring jdbcTemplate along with Java.

The structure of the project would be like below


Database we are using is MYSQL.


Below is the Program




Above is the schema and the query of the schema is as below

CREATE TABLE `Organization` (
  `id` int(11) NOT NULL,
  `slogan` varchar(45) DEFAULT NULL,
  `totalEmployee` int(11) DEFAULT NULL,
  `yearOfIncorporation` int(11) DEFAULT NULL,
  `name` varchar(45) DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


You can download the full program from my git hub CLICK HERE


Hope this will help you in understanding the Coding part . If you face any issue please leave us a comment , Happy to help you :)


Thanks for reading
Noeik



Saturday, November 4, 2017

Program to get all the substring of the string in java

Hey all , this is queit popular interview question to write the program to find all the substring of the string in java

In my earlier post I have talked about Tower of Hanoi problem 
You can also see other Sorting program
Bubble Sort 
Selection Sort
Insertion Sort 

Here is my program

PROGRAM OF INSERTION SORT IN JAVA





The Time Complexity of the Program is - O(nlogn)


Output of the program

n
no
noe
noei
noeik
o
oe
oei
oeik
e
ei
eik
i
ik

k






Program of Random Function baised with 50% for 0 and 1 and 75% for 1 and 25% for 0 in java

Hey guys , Today one of my friend asked me a question regarding the function which will return the baised probability of 75% of 1 I thought lets share the answer with you guys as well

So below is my solution of the problem and my approach.


Approach 

  • First will write one function which will return 50% probability of getting 0 and 1
  • After that will create one function which call 50% function of 2 times.
  • Will return the OR of the the response.


Below is the program 

Thanks for reading
Noeik

Tuesday, October 31, 2017

Spring - Inversion of Control (IOC ) Programming Example with Spring xml

Spring , one of the most popular DI (Dependency Injection) framework used in Enterprise now. There are so many feature of spring because of which it is using so much in market right now but the most important and the core feature is IOC i.e Inversion of Control.

So What is Inversion Of Control (important Point for Interview as well ) - So basically IOC is as words suggest the responsibility of Creating and Maitaining the lifecycle of Object is of Spring Container only , We as Developer don't need to maintain the lifecycle of Object (in spring its called as bean).

So let see the Example of IOC in Spring-

1)Create the Java maven project in eclipse.
2) If you have created simple java project using maven , it will have below structure.
3) As per my Project you can create one package (as in my com.vp.spring)
and see the below code




4) By Watching above program you can see all the Code.

If you want to understand about IOC in depth , Read from Official Documents

Download full Project from here   



If you have any problem , leave me a comment will help you in understand.


Thanks for reading
Noeik

Sunday, September 10, 2017

Apache ActiveMQ "Message Queue" and its implementation using java

Hello Guys , Hope you all are doing good , Today we will learn more about activemq so lets get start.

What is ActiveMQ ?
Apache ActiveMQ ™ is the most popular and powerful open source messaging and Integration Patterns server.

Apache ActiveMQ is fast, supports many Cross Language Clients and Protocols, comes with easy to use Enterprise Integration Patterns and many advanced features while fully supporting JMS 1.1 and J2EE 1.4. Apache ActiveMQ is released under the Apache 2.0 License

It provide message queue which we can use to publish our message and can create subscriber to get the data from message topic

What is the use of Active MQ ?
Active MQ  where "MQ" stands for message queue  is widely used for the distributed systems where we want one system should not wait for the other system to complete it task , so what basically we do , we provide active mq where one (System A) complete it task put the data in message queue and starts working on other task , (System B ) will get the data stored in message queue by System A and will starts its working on that also , there is a Data delivery Guarantee also a key feature.

So lets see the implementation of Active MQ using java

Download the ActiveMQ Server from here : DOWNLOAD NOW

Maven Dependency

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-core</artifactId>
    <version>5.7.0</version>
</dependency>

<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.10</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>




Consumer Code
Producer Code

Main Class

The Full Source Code you can download from my git respository : DOWNLOAD FULL SOURCE

If you have any issue regarding the program execution , leave me a comment , Will try our best to resolve the program

Thanks for reading
-Noeik


Sunday, July 23, 2017

Program of Linked List Insertion and Deletion Operations in java

Linkedlist as we all know is one of the most important topic of interview especially for coding round.

We will not talk more about the theoretical part of linked list

Program for the insertion and deletion operation of linkedlist.


In my earlier post I have talked about Tower of Hanoi problem 
You can also see other Sorting program
Bubble Sort 
Selection Sort
Insertion Sort 

Main Class File




Hope this will help you in understand the program , Let me knowif you guys facing any problem in understanding this .


Thanks for reading.
-Noeik

Monday, July 3, 2017

Hibernate Mapping - OneToOne Relationship

Hello friend , Knowing one to one relation is very easy to understand for the interview aspirant , but to implement the knowledge into programming is the key which makes one a good programmer.

Today we will learn more about hibernate mapping -One to one

Breif- There are FOUR relationship mapping between object (tables)

  • ONE TO ONE
    • Unidirectional 
    • bidirectional
  • ONE TO MANY
    • Unidirectional 
    • bidirectional
  • MANY TO ONE
    • Unidirectional 
    • bidirectional
  • MANY TO MANY 
    • Unidirectional 
    • bidirectional

One to One mapping- In One to One mapping one object (row of a table ) is associated only with one another object(row of a table)

Ex - A user have only one System Credential.

When we say Uni directional - it means we dont have target to source mapping , we only have source to target mapping.
But in bidirectional we will have source to target to and fro mapping.

In Today's post we will see the ONE TO ONE UNIDIRECTION PROGRAM-

The Project Structure should be like below













SQL Scripts
CREATE TABLE `finances_user` (
  `USER_ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `FIRST_NAME` varchar(45) NOT NULL,
  `LAST_NAME` varchar(45) NOT NULL,
  `BIRTH_DATE` date NOT NULL,
  `EMAIL_ADDRESS` varchar(100) NOT NULL,
  `LAST_UPDATED_BY` varchar(45) NOT NULL,
  `LAST_UPDATED_DATE` datetime NOT NULL,
  `CREATED_BY` varchar(45) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  `USER_ADDRESS_LINE_1` varchar(100) DEFAULT NULL,
  `USER_ADDRESS_LINE_2` varchar(100) DEFAULT NULL,
  `CITY` varchar(100) DEFAULT NULL,
  `STATE` varchar(2) DEFAULT NULL,
  `ZIP_CODE` varchar(5) DEFAULT NULL,
  PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;


CREATE TABLE `credential` (
  `CREDENTIAL_ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `USER_ID` bigint(20) NOT NULL,
  `USERNAME` varchar(50) NOT NULL,
  `PASSWORD` varchar(100) NOT NULL,
  PRIMARY KEY (`CREDENTIAL_ID`),
  UNIQUE KEY `USER_ID_UNIQUE` (`USER_ID`),
  CONSTRAINT `FINANCES_USER_FK` FOREIGN KEY (`USER_ID`) REFERENCES `finances_user` (`USER_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


DOWNLOAD - SOURCE CODE (if deleted let us know)

Let us know if you dont understand anything in this post .

Thanks for reading 
-Noeik




Saturday, June 17, 2017

Program to find whether the Book is on Public link or not

In this post we will try to understand whether the book is on public link or not.
First question someone ask would be , What is meant by public link ??

PUBLIC LINK- Public link is referred as the links where all the contents are free to use , there is no copy right problem if we use the content of the website.

Objective: I have got the problem where we need to check whether the Book with particular ISBN is present on public link or not.
To check that , we first know the public links are , so few are (which i am checking ) -
https://archive.org/
googlebooks
https://www.gutenberg.org/


Problem- User will provide one isbn number and we need to return whether the isbn is presented on public link or not.

Solution approach- We will provide the api where the user will provide the isbn and we will return the true or false.

Internally , we are using the rest api which will connect with the mentioned public link and provide us where the book is on these site or not using the isbn no.


you can get the Project from here- 
https://github.com/visparashar/ISDNDemo

You can contribute on this project , if you guys have some good idea.

Hope you learn something new. BTW this task i have completed and got some money from freelancer.com

Want to become freelancer .JOIN HERE

Tuesday, February 7, 2017

Garbage Collector and its Algorithms - JAVA

-------------------Garbage Collection-----------------------
In java , programmer need not to care about the objects which are no longer in use. garbage collector
destroy those objects and make the memory available for the programmer to use again.
- garbage collector not guaranteed to run at any specific time.
there are few method of garbage collector



------------The finalize () method:
Called by the garbage collector on an object when garbage collector determines that there are no more references to the object
Note :

The finalize method is never invoked more than once by a Java virtual machine for any given object.
Our program must not rely on the finalize method because we never know if finalize will be executed or not.

----------------gc() – request to JVM

We can request to run the garbage collector using java.lang.System.gc() but it does not force garbage collection, the JVM will run garbage collection only when it wants to run it.­­
We may use system.gc() or runtime.gc()
import java.lang.*;
public class Test
{
    public static void main(String[] args)
    {
        int g1[] = { 0, 1, 2, 3, 4, 5 };
        System.out.println(g1[1] + " ");

        // Requesting Garbage Collector
        System.gc();
        System.out.println("Hey I just requested "+
                          "for Garbage Collection");
    }
}

--------What happens when group of object only refer to each other?

It is possible that a set of unused objects only refer to each other.
This is also referred as Island of Isolation.
For example, object o1 refers to object o2. Object o2 refers to o1. None of them is referenced by any other object.
In this case both the objects o1 and o2 are eligible for garbage collection.


-------------------ALGORITHM USED BY Garbage Collector to remove objects.
Garbage Collector uses 2 alogrithm to remove objects

* Mark and sweep Algorithm
* Island of isolation


-------------------Mark and sweep alogrithm-------------
The main activity of garbage collector is to first identify the unused objects and them claim the head memory to available for use.
There are 2 phase to perform in marks and sweep alogrithm-
1) mark phase
2) sweep phase

In Mark Phase , whenever any object is created its mark bit is set to be false (0) , so in mark phase we set all the reachable object marked bit as true(1),
to perfome is operation , we simply do graph traversal , deepth first search in particular, here we consider all objects as nodes ,and all the nodes connected to one nodes are visited and set as true.

Root is a variable that refer to an object and is directly accessible by local variable. We will assume that we have one root only.
We can access the mark bit for an object by: markedBit(obj).

In Sweep Phase : In sweep phase , all the unreachable objects are sweeped , i.e all the objects whose marked bits are false , will be remove heap memory.
and then the marked bit of all the reachable object will again sets as false , so that they will be again available to recurring process.


------------Island of Isolation -----------------------

Object 1 references Object 2 and Object 2 references Object 1. Neither Object 1 nor Object 2 is referenced by any other object. That’s an island of isolation.
Basically, an island of isolation is a group of objects that reference each other but they are not referenced by any active object in the application. Strictly speaking, even a single unreferenced object is an island of isolation too.

Design Pattern

Design Pattern
-----------------
* Creatational Design Pattern- the way to create object.
used when we need to make decision for creating the instance of class.
Type-
1) Factory Design pattern- It says that let create the abstract class or interface for creating an object but let the subclass decide which class to instanciated.
 * also known as virtual constructor

 Ex -

 package inv.learning.designpattern;


interface Animal{

String name="";
String getType();

}
class Dog implements Animal{

@Override
public String getType() {
// TODO Auto-generated method stub
return "Dog";

}

}
class Cat implements Animal{

@Override
public String getType() {
// TODO Auto-generated method stub
return "Cat";

}

}

class AnimalFactory{

static Animal getAnimal(String str){
if(str==null)
return null;
else if (str.equalsIgnoreCase("CAT"))
return new Cat();
else if (str.equalsIgnoreCase("DOG"))
return new Dog();
else
return null;
}

}
public class FactoryDesign {

public static void main(String[] args) {
// AnimalFactory factory = new AnimalFactory();
Animal dog = AnimalFactory
.getAnimal("Cat");
System.out.println(dog.getType());
Animal cat= AnimalFactory.getAnimal("DOG");
System.out.println(cat.getType());
}

}

------------------------------------------------------------------------------------------------------
2) Abstract Factory Pattern-define an interface or abstract class for creating families of related (or dependent) objects but without specifying their concrete sub-classes.



-------------------
3) Singleton Design pattern- define a class which only have one instance and provides a global  point of  access to it.

Ex -
public class Singleton {

public static void main(String[] args) {
MySingletonClass temp=MySingletonClass.getInstance();


}

}
class MySingletonClass {

private final static MySingletonClass myclass=null;
private MySingletonClass(){}
static MySingletonClass getInstance(){
if(myclass == null)
return new MySingletonClass();
else
return myclass;

}
}

----------------------------
3) Prototype design pattern- cloning of an existing object instead of creating new one and can also be customized as per the requirement.
we use this pattern when creating object is expensinve.
t reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing which type of object it will be.
It lets you add or remove objects at runtime.

Example-

public class Prototype {
public static void main(String[] args) {
Employee emp= new Employee(10, "vishal", "g4s");
System.out.println("address of first emp object "+emp.address);
Employee emp2=(Employee)emp.getClone();
System.out.println("address of sec emp object "+emp2.address);
}
}
interface InfPrototype{
InfPrototype getClone();
}
class Employee implements InfPrototype
{ int age;
String name;
public String address;

public Employee(){

}
public Employee(int age,String name,String address)
{
this.age=age;
this.name=name;
this.address=address;
}
@Override
public InfPrototype getClone() {
// TODO Auto-generated method stub
return new Employee(age,name,address);
}

}
--------------------------------
4) Builder Design Pattern-  wehen we construct a complex object from simple object using step by step approach.
It provides clear separation between the construction and representation of an object.
It provides better control over construction process.
It supports to change the internal representation of objects.


-----------------------------------------------------------------------------------------------------------------------
STRUCTURAL DESIGN Pattern-simplifies the structure by identifying the relationships

1) Adapter Design Pattern- converts the interface of a class into another interface that a client wants
 it is also known as wrapper.
 When an object needs to utilize an existing class with an incompatible interface.
When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.
When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.



2)Bridge Pattern-Decouple the functional abstraction from the implementation so that the two can vary independently
The Bridge Pattern is also known as Handle or Body.

When you don't want a permanent binding between the functional abstraction and its implementation.
When both the functional abstraction and its implementation need to extended using sub-classes.
It is mostly used in those places where changes are made in the implementation does not affect the clients.

Thanks for reading
-Noeik

Breadth first Traversal(BFT) AND Depth First Traversal(DST) Program in java

Hello Guys , Hope you all are doing good , so today we are going to see the BST and DST Program in java.

Let see the implementation of BST and DST in single program


package inv.learning.searching;

import java.util.Iterator;
import java.util.LinkedList;

public class BFT {

public static void main(String[] args) {

Graph g = new Graph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 4);
System.out.println("Breadth First Search --");
g.BST(0);

System.out.println("Depth first search --");
g.DST(0);

}
}
class Graph{

int V;
LinkedList adj[];

Graph(int v){
V=v;
adj = new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]= new LinkedList<>();
}
}
public void addEdge(int v,int w)
{
adj[v].add(w);
}

public void BST(int s)
{
boolean[] visited = new boolean[V];
visited[s]=true;
LinkedList<Integer> queue= new LinkedList<>();
queue.add(s);
while(queue.size()!=0)
{
int n = queue.poll();
System.out.println(n+" ");
Iterator<Integer> itr = adj[n].listIterator();
while(itr.hasNext())
{
int i = itr.next();
if(!visited[i]){
visited[i]=true;
queue.add(i);
}

}
}

}
public void DST(int s){
boolean[]  visited = new boolean[V];

DSTUtil(s, visited);
}

public void DSTUtil(int s, boolean[] visited){
visited[s]=true;
System.out.println(s+" ");
Iterator itr = adj[s].listIterator();
while(itr.hasNext())
{
int i = (int) itr.next();
if(!visited[i])
{
DSTUtil(i, visited);

}
}


}


}

Output-

Breadth First Search --


Depth first search --


Thanks for reading
-Noeik

JVM - Classloading in java

Hello Everyone , Hope you all are doing good , Today we will learn about class loading in java , class loading is very basic topic which most of the programmer dont know, so lets see what and type of classloaders.

--jvm Class Loading---
Three activities while class loading
-loading
-linking
-initialization


Loading--- The class loader reads the .class files and generate the correposnidn binary data.

Let see this with example

import java.lang.reflect.Method;

public class ClassLoading {

public static void main(String[] args) {
Student s1= new Student();
Class c1= s1.getClass();

System.out.println(s1.getClass().getName());
Method[] m = s1.getClass().getMethods();
for(Method m1:m)
{
System.out.println(m1.getName());
}
Student s2 = new Student();
Class c2= s2.getClass();
System.out.println(c1==c2);
}


}


class Student {

String name;
int roll_no;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}

}

Output----
inv.learning.jvm.Student
getRoll_no
setRoll_no
getName
setName
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
true


NOTE: If we see the line System.out.println(c1==c2) it will give true that means Class c1 and Class c2 always point to same Class Object.
For every loaded .class file, only one object of Class is created.

--------------------------------------------------------
Linking-- Performs verification, preparation, and (optionally) resolution.
Verification : Its ensure the correctness of .class file if not generated by valid compile it will give the runtime exception.
Preparation : JVM allocates memory for class variables and initializing the memory to default values.
Resolution : It is the process of replacing symbolic references from the type with direct references. It is done by searching into method area to locate the referenced entity.

----------------------

Initialization:- In this phase all the static variable and static blocked get the assigned values in the code , it executed from top to bottom and from parent to child.
basically there are 3 type of class loader.
1) Bootstrap class loader- These class loader is essential used to load the trusted classes. Like all the native java api classes which are defined in JAVA_HOME/jre/lib.
2)Extension class loader- child of bootstrap class loader , load all the class of JAVA_HOME/jre/lib/ext .
3) Application class loader - child of extension class loader , used to load the application .class files.

package inv.learning.jvm;

public class ClassLoadingDemo {

public static void main(String[] args) {

// String class is loaded by bootstrap loader, and
        // bootstrap loader is not Java object, hence null
System.out.println(String.class.getClassLoader());

System.out.println(ClassLoadingDemo.class.getClassLoader());
}
}

Thanks for reading
-Noeik

Monday, February 6, 2017

Polymorphism and its type-Java

Hello guys , today we will read about one important characteristice of oops i.e Polymorphism

--polymorphism---

One thing in many form
or
The ability to appear in more than one form

In Java there are 2 type of polymorphism
-compiler time polymoriphism (static binding) -achieved by method overloading

-runtime polymorphism(dynamic binding) -achieved by method overriding

---Overloading---------------
there are 2 type of overloading in java
-method overloading
-constructor overloading
-operator overloading

-------------------------------Method Overloading----------------------------------
If the class contains more than one method with same name and different no. of arguments(return type is not consider in overloadding) or same no. of argument with different data types.
Ex -
class c{
void m1(int a)
void m1(int a , int b)
void m2(char c)
void m2(String str)

}
Method signature - method name and paramters is metehod signature
Real time example-
for Adhar Card we have few options to get the duplicate adhar card
we can provide- dob and name
pan no
name and father name
so here we will use method overloading as we dont know what the user is going to give to fetch its information.

--------------------------------Constructor Overloading--------------
Same constructor name with different no. of arguments or same constructor with same no. of arguments with different data type.

Ex-
class Test
{
Test(int i)
{
syso("one arg constructor with int");
}
Test(int i, int k)
{
syso("2 arg constructor with int");
}
Test(char cs)
{
syso("one arg constructor with char");

}
main()
{
Test t=new Test(1);
Test t1 = new Test(1,2);
Test t3 =new Test('r');

}
}
------------------operator overloading--------------
one operator with more than one behaviour
no java is not supported operator overloading

Only one operator + is defined in java implisitly

Root class of all class is object class
Default package in java is java.lang package


-----------------------------Method Overriding-----------------------------------
To Achieve the overriding we required 2 java classes with inheritance concept

Overriden class is the parent class whose method is going to override
overriding class is the child class whose method will override the parent method
There are some rules of Method Overriding
1) Overridden method signature and child class method signature must be same
2) Return type of both the method must be same at primitive level
3)co varint return type in which the parent class has parent return type and class method is having the sub type of parent return type
4) if a method is declared as final overriding is not possible
-final class methods are final(bcz if it is not a final we will be able to override) but variable is not final
5) static method can't be override
6)child class is not able to hold the parent reference object
ex - Child child = new Parent() // invalid


Hope these points will help you in your preparation .

Thanks for reading
-Noeik



Thursday, February 2, 2017

Basic and tricky java Interview Questions

Hi guys , Hope you all are doing good , Today I am going to share few tricky questions which i felt everyone who is preparing for java interview should know. So lets see

Q1) Difference between new operator and newInstance() method ?/
-    new is used when we know the type of class instance know at design time.
     if you dont know then we use newInstance method
    ex-
     Student std = new Student();
      Object o = Class.forName(arg[0]).newInstance();


Q2) classNotFoundException vs NoClassDefFoundException
       when we write like this
      Test test= new Test();
      and the Test.class file is not found then at runtime we will get NoClassDefException found.                (unchecked exception)
         Object o = Class.forName(args[0]).newInstance();
        will get the ClassNotFoundException (checked exception)



Q3) Diff b/w checked and unchecked exception
exception which are be checked by compiler  how to handle the expection. for the smooth execution of program.
ex- FileNotFoundException is checked exception , compiler ask to handle the exception while compile.
exception which are not checked by compiler
ArthematicException is unchecked exception.


control flow of try catch
if exception in araised in catch block it is abnormal exception

variable combination of try catch final block
- try catch
-try catch catch(catch should be in child to parent heirarchy)
try final
try catch final


------------------String---------------
Why String is always final in java - due to immutability ,security (thread safe) etc
Why we use character array over string to store password ?
-as string is immutable and it is persist till the garbage collector called . As data is stored for long time because string pool used the string data
- if we use JPasswordField then it will also return array[] for getPassword() and depricated getText() field

--------------String Pool-----------------
Why we use string pool ?
String pool is used to store the references of the strings
Ex-
String s=“prasad”;
String s1=“prasad”;
System.out.println(s==s1)  // output  true;

The class is loaded when JVM is invoked.
JVM will look for all the string literals in the program
First, it finds the variable s which refers to the  literal “prasad” and it will be created in the memory
A reference for the literal “prasad” will be placed in the string constant pool memory.
Then it finds another variable s2 which is referring to the same string literal “prasad“.
Now that JVM has already found a string literal “prasad“, both the variables s and s2 wil refer to the same object i.e. “prasad“.
----intern() --------------
intern method check whether the string is present in spring pool if yes then return the reference of the string otherwise create new string object
Ex-
String s ="prasad";
String s1="prasad".intern();
System.out.println(s==s1)  // output true
System.out.println(s.equals(s1));   // output true

String s ="prasad";
String s1="prasad1".intern();
System.out.println(s==s1)  // output false
System.out.println(s.equals(s1));   // output false

---------------------------

Difference btw encapculation & abstraction(how to achieve abstraction using encp)
- by decreasing the scope of behaviour(methods)
encapsulation - wrapping of data and associated func into a single unit is encp -(class)
Ex-
if we have one function which will call the other function so we can scope down the other function to achieve abstraction

Class A{

public void m1()
{
m4internal();
}
public void m2()
{
}
}
Class B{

protected void m4internal()

}

Hope these will be helpful for you , if you have any problem , do let me know

Thanks for Reading
-Noeik

Thursday, January 12, 2017

Inheritance - Indepth- Important Topic of Interview of Java

Hi Guys, Yesterday I posted about Inheritance , what how and type of inheritance . today i am going to post articles about the Indepth knowledge of inheritance, So lets starts

HOW TO PREVENT THE CLASS FROM INHERITANCE
to prevent the class from inherit , we should use final modifier
Ex-
Class A{
}
Class B extends A{
}
OUTPUT - inheritance possible
final Class A{
}
Class B extends A
{
}
Output -inheritnace not possible as class is final (cannot inherit from final )

this keyword - to indicate the current object
super keyword is used to indicate the parent object of the current Object

USE OF SUPER KEYWORD IN INHERITANCE

Class Parent{

Parent()
{
syso("this is parent 0-arg constrctr");
}
}
Class Child extends Parent
{
Child()
{
this(10)    // to call child 1 args constructor
syso("child 0-arg constructor")
}
Child(int agr)
{
super()  // to call parent 0 args constructor
syso ("child 1-arg constructor");
}

psvm(string[] args)
{
new Child();
}
}
NOTE - SUPER & THIS CALL MUST BE FIRST STATEMENT IN CONSTRUCTOR
NOTE 2 - SUPER & THIS BOTH CANT BE POSSIBLE TO CALL IN SAME CONSTRUCTOR
NOTE 3- CHILD CLASS CONSTRUCTOR WILL ALWAYS CALL ANOTHER CONSTRUCTOR EITHER EXPLICIT OR IMPLICIT IF WE DON'T SPECIFY THE CONSTRUCTOR THEN SUPER() WILL BE CALLED

* compiler generated code always called zero argument constructor
* if we created one arg constructor then we will have to create zero arg constructor else it will generate compiler error

Instance block execute first then constructor execute (in inheritance case - parent class instance block then child class instance block)

Hope you guys understand the points i am trying to make, Let me know if you have any problem , Will be happy to help

-Thanks for Reading
-Noeik

Tuesday, January 10, 2017

Inheritance- Basics - Important Topic for Interview

Guys , Hope you are doing well , Today i am again back with some good article , today i will try to write something which i think is one of the favorite topic of all time for an interviewer.

So Inheritance , Most of you knows what is inheritance but the actual in depth knowledge of inheritance is very much required while you are preparing for interview.
In my earlier post I have talked about Tower of Hanoi problem 
You can also see other Sorting program
Bubble Sort 
Selection Sort
Insertion Sort 
  • What is Inheritance  ?
    • In general - acquiring the properties and character tics of parent by child. 

 
Class A   // parent class
{ void m1();
void m2();
}
Class B extends A   // child class(class B has method m1 & m2 available)
{
void m3();
void m4();
}

ADVANTAGES OF INHERITANCE

-reduce the redundance 
- reduce the length of code;

NOTE - One class only extends one class (not more than one class)

B b = new B();  // we can access 4 method using b object;
A a = new A();   // only access 2 methods;

Interview Question - recommended to create the object of parent or child class ?? 
ans - child - bcz it is possible to access parent method also;

NOTE - root class is the class which is not extending any class.
-- root class of all java classes -> Object class (package java.lang )

TYPE OF INHERITANCE-

  • -single level inheritance
  • -multiple inheritance
  • -multilevel inheritance
  • -hirarical inheritance
  • -hybrid inheritance
---SINGLE LEVEL INHERITANCE---
when a class is extending only one parent class and the class is not extended by any other class
Ex- 
Class A {
void m1()
}
Class B extends A 
{

void m2()
}

---multilevel inheritance
Ex- 
Class A {
void m1()
}
Class B extends A{
void m2()
}
Class C extends B {
void m3()
}

--heirarical inheritance

Ex 
Class A
{
}
Class B extends A
{
}
Class C extends A
{
}
Class D extends A
{
}

--multiple inheritance

Ex
Class A
{
void money ()

}
Class B 
{
void money ()
}
Class C extends B, A
{
}
 NOTE - now when c is trying to access , then obviously ambiguity occured for c object which method to call(SO IT IS NOT SUPPORTED BY JAVA)(diamond problem )
 --HYBRID INHERITANCE = MULTIPLE + HEIRARICAL  (java is not supporting multiple so java is not supporting hybrid)


In Next Article we will have Inheritance in depth article , If you have any problem in this post , do let me know , I will try to solve your problem , Do Comment in comment section .

Thanks for Reading

-Noeik