Java Generic

Java Generic :

A parameterized type that operates by a class or an interface is called generic. It is introduced in java-5. It facilitate to write algo which is independent from any specific data type and type safety.

Through Generic its possible to create a single class or method that automatically works with all data types such as Integer, String Float, Double etc. It provide ability to reuse existing code safely and easily.

Note : Generic works only with Object type such as Integer, Float. It can’t work with primitive type.

Example :

You can better understand Generic through below code :


package com.pkjavacode.com;

/**
*
* @author pradeep
*/
public class GenericTest {

public static void main(String args[]) {

GenericExample<Integer> gt = new GenericExample(50);
int a = gt.getObject();
System.out.println(a);
GenericExample<String> gt2 = new GenericExample("Pradeep Yadav");
String b = gt2.getObject();
System.out.println(b);
}
}

class GenericExample<T> {

T obj;

public GenericExample(T obj2) {
obj = obj2;
}

public T getObject() {
return obj;
}
}

Output :

50
Pradeep Yadav

Unicode System in java

Unicode System :

Unicode is a universal international standard character encoding which is capable of representing all the world’s written
languages.
Why java uses Unicode System?
Prior Unicode system, there were many language standards:

  • ASCII : It stand for American Standard Code for Information Interchange used for the United States.
  • ISO 8859-1 : It was used for Western European Language.
  • KOI-8 : Used for Russian.
  • GB18030 and BIG-5 : Used for chinese, and so on.

With these languages standard arise two problems:

  • A particular code value corresponds to different letters in the various language standards.
  • The encodings for languages with large character sets have variable length. Some common characters are encoded as single bytes, other require two or more byte.

To solve these problems, a new language standard was developed i.e. Unicode System.

In unicode, character holds 2 byte, so java uses 2 byte for characters.

  • lowest value are: \u0000 and
  • highest value are: \uFFFF

What is IS-A and HAS-A relationship in java

IS-A and HAS-A relationship in java :

IS-A relationship :

IS-A relationship is based on class inheritance or interface implementation. You can say that “this thing is a type of that
thing”.
Example :

Suppose you have a class Vehicle and another class Car extending Vehicle class. So you can say that a Car is a
Vehicle i.e. Car IS-A Vehicle.

Syntax :


public class Vehicle{
//some code here!
}

public class Car extends Vehicle{
//some code here!
}

 

HAS-A relationship :

It is based on usage rather than inheritance. Suppose a class Vehicle and other class Car which extending Vehicle class and
in class Car contain a reference variable of class Vehicle like below..


public class Vehicle{
//some code here!
}

public class Car{
private Break mybreak;
//some logic here!
}

In above code class Car has an instance variable type of Break. So you can say ..
Car HAS-A Break.

Note : HAS-A relationship allows us to design classes that follow good OO practices which help reduce bugs.

Tokenizing in java

Tokenizing :

Tokenizing is a mechanism of taking larg pieces of source data, breaking them into small pieces, and storing these small pieces in variables.

Example :
The most common tokenizing situation is reading a delimited file in order to find the contents of the file and moved into useful places such as objects, arrays and collections.
There are two classes in the java API that provides tokenizing mechanism :

  •  String
  • Scanner                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               Both classes provide many methods which is useful in tokenizing.

What is token and delimiter?

Token is just a actual piece of data and delimiters are the expression that used to separate token from each other, it may be a comma, a backslashes or a single whitespace.

Example :


package com.pkjavacode.com;

import java.util.StringTokenizer;

public class TokenizingDemo {

/**
 * @param args
 */
 public static void main(String[] args) {
String str = "I am pradeep kumar yadav";
 String[] tokens = str.split(" ");
 System.out.println("Count tokens" + tokens.length);
 for (String s : tokens) {
 System.out.println(" " + s);
 }
 }
}

Output :

I
am
pradeep
kumar
yadav

Tokenizing with Scanner class :

When you need to do serious tokenizing you go for Scanner. It’s have following feature :

  • Scanners can be constructed using files, streams and Strings as a source.
  • Tokenizing mechanism is performed within a loop so that you can exit the process at any point.
  • Tokens can be converted to their appropriate primitive types automatically.

Example :


package com.pkjavacode.com;

import java.util.Scanner;

public class TokenizingScannerExample {

/**
* @author pradeep
*/
public static void main(String[] args) {
String str = "I am Pradeep Kumar Yadav";
Scanner s = new Scanner(str);
String s2;
while (s.hasNext()) {
s2 = s.next();
System.out.println("" + s2);
}
}
}

Output :

I
am
Pradeep
Kumar
Yadav

Find factorial with recursion

Find factorial with recursion method :

recursion is a process where a method called within itself.


package com.pkjavacode.com;

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

/**
*
* @author pradeep
*/
public class FactorialExample {

int fact(int n) {
if (n == 0) {
return 1;
} else {
return n * fact(n - 1);
}
}

public static void main(String[] args) {
FactorialExample f = new FactorialExample();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter a number :");
int b = Integer.parseInt(br.readLine());
int a = f.fact(b);
System.out.println("Factorial are :" + a);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output :

Enter a number :
5
Factorial are :120

print triangle shape

Print triangle :

 


package com.pkjavacode.com;

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

/**
*
* @author pradeep
*/
public class TriangleShape {

public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter a number :");
int n = Integer.parseInt(br.readLine());
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n - i; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output :

Enter a number :
4
*
***
*****
*******
*********

How to print diamond shape in java

Diamond shape :

 


public class DiamondShape {

public static void main(String[] args) {
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 try {
 System.out.println("Enter a number :");
 int n = Integer.parseInt(br.readLine());
 for (int i = 0; i <= n; i++) {
 for (int j = 0; j <= n - i; j++) {
 System.out.print(" ");
 }
 for (int j = 0; j <= i; j++) {
 System.out.print("*");
 }
 for (int j = 0; j < i; j++) {
 System.out.print("*");
 }
 System.out.println();
 }

for (int i = 1; i <= n; i++) {
 for (int j = 0; j <= i; j++) {
 System.out.print(" ");
 }
 for (int j = 0; j <= n - i; j++) {
 System.out.print("*");
 }
 for (int j = 0; j < n - i; j++) {
 System.out.print("*");
 }
 System.out.println();
 }

} catch (Exception e) {
 e.printStackTrace();
 }
 }
}

Output :

Enter a number :
4
*
***
*****
*******
*********
*******
*****
***
*