Order by , Group by in Java

This is one of the rare requirement like if you want sort some data and you wants to segregate the data by grouping some factor.

Here players are sorted by rank,remunation  and we are grouping them by gametype .

 
package com.java8.practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

public class Collectors_reducing {
public static void main(String[] args) {
PersonPojo personPojo = new PersonPojo(1, "MESSI", 250f, "Football");
PersonPojo personPojo3 = new PersonPojo(3, "Ronaldhino", 150f, "Football");
PersonPojo personPojo2 = new PersonPojo(2, "Inesta", 100f, "Football");

PersonPojo personPojo4 = new PersonPojo(5, "Nadal", 140f, "Tennis");
PersonPojo personPojo5 = new PersonPojo(7, "Ivanovic", 55f, "Tennis");
PersonPojo personPojo6 = new PersonPojo(4, "Federer", 170f, "Tennis");

System.out.println("-------------Order By Rank, Group by GAMENAME-----------------------");

ArrayList arrayList = new ArrayList(
Arrays.asList(personPojo, personPojo2, personPojo3, personPojo4, personPojo6, personPojo5));
Comparator comparator = Comparator.comparing(PersonPojo::getPlayerRank);
Map<String, Optional> map = arrayList.stream().collect(
Collectors.groupingBy(PersonPojo::getGameName, Collectors.reducing(BinaryOperator.minBy(comparator))));
map.forEach((k,
v) -> System.out.println("---" + k + "----" + ((Optional) v).get().getPlayerName() + "---"
+ ((Optional) v).get().getPlayerRank() + "---"
+ +((Optional) v).get().getPlayerRemunation() + "---"
+ ((Optional) v).get().getGameName()));

System.out.println("---------------------------Order BY remunation, Group by GameName------------------");
Comparator comparator2 = Comparator.comparing(PersonPojo::getPlayerRemunation);
Map<String, Optional> map2 = arrayList.stream().collect(Collectors
.groupingBy(PersonPojo::getGameName, Collectors.reducing(BinaryOperator.minBy(comparator2))));

map2.forEach((k,
v) -> System.out.println("---" + k + "---" + ((Optional) v).get().getGameName() + "---"
+ ((Optional) v).get().getPlayerName() + "---"
+ ((Optional) v).get().getPlayerRank() + "---"
+ ((Optional) v).get().getPlayerRemunation()));

}
}

class PersonPojo {
private int playerRank;
private String playerName;
private float playerRemunation;
private String gameName;

public String getGameName() {
return gameName;
}

public void setGameName(String gameName) {
this.gameName = gameName;
}

public int getPlayerRank() {
return playerRank;
}

public void setPlayerRank(int playerRank) {
this.playerRank = playerRank;
}

public String getPlayerName() {
return playerName;
}

public void setPlayerName(String playerName) {
this.playerName = playerName;
}

public float getPlayerRemunation() {
return playerRemunation;
}

public void setPlayerRemunation(float playerRemunation) {
this.playerRemunation = playerRemunation;
}

public PersonPojo(int playerRank, String playerName, float playerRemunation, String gameName) {
this.playerRank = playerRank;
this.playerName = playerName;
this.playerRemunation = playerRemunation;
this.gameName = gameName;
}

@Override
public String toString() {
return "PersonPojo [playerRank=" + playerRank + ", playerName=" + playerName + ", playerRemunation="
+ playerRemunation + ", gameName=" + gameName + "]";
}

}

output:

————-Order By Rank, Group by GAMENAME———————–
—Tennis—-Federer—4—170.0—Tennis
—Football—-MESSI—1—250.0—Football
—————————Order BY remunation, Group by GameName——————
—Tennis—Tennis—Ivanovic—7—55.0
—Football—Football—Inesta—2—100.0
Picked up _JAVA_OPTIONS: -Xmx512M

Advertisements

sort by id , name -custom sorting

Student.java:

package com.me.pack;

import java.util.Comparator;

@SuppressWarnings(“rawtypes”)
public class Student implements Comparable {
private int id;
private String name;
private float sal;

public static final Comparator idComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.id – o2.id;
}
};

public static final Comparator nameComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.name.compareTo(o2.name);
}
};

public static final Comparator salComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return (int) (o1.sal – o2.sal);
}
};

public static final Comparator comp=
(Student s1, Student s2) -> s1.getName().compareTo(s2.getName());

@Override
public int compareTo(Student arg0) {
// TODO Auto-generated method stub
return this.id – arg0.id;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

public float getSal() {
return sal;
}

public void setSal(float sal) {
this.sal = sal;
}

public Student(int id, String name, float sal) {
super();
this.id = id;
this.name = name;
this.sal = sal;
}

@Override
public String toString() {
return “Student [id=” + id + “, name=” + name + “, sal=” + sal + “]”;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(sal);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(sal) != Float.floatToIntBits(other.sal))
return false;
return true;
}

}

 

Test.java:

package com.me.pack;

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

public class ComparatorStudentLamda {
public static void main(String[] args) {
Student student = new Student(125, “bcv”, 546.09f);
Student student2 = new Student(123, “mno”, 123.09f);
Student student3 = new Student(130, “fgh”, 74357.09f);

List list = new ArrayList(Arrays.asList(student, student2, student3));
for (Student studenttemp : list) {
System.out.println(studenttemp);
}
System.out.println(“—————–“);
Collections.sort(list, Student.idComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.nameComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.salComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.comp);
for (Student studentR : list) {
System.out.println(studentR);
}
}
}

 

 

Invoke from java8:
Collections.sort(list, Student.comp);
for (Student studentR : list) {
System.out.println(studentR);
}

 

output:

Student [id=125, name=bcv, sal=546.09]
Student [id=123, name=mno, sal=123.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=123, name=mno, sal=123.09]
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
Student [id=123, name=mno, sal=123.09]
—————–
Student [id=123, name=mno, sal=123.09]
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
Student [id=123, name=mno, sal=123.09]
Picked up _JAVA_OPTIONS: -Xmx512M

refer : http://www.concretepage.com/java/jdk-8/lambda-expressions-java-8-examplehttp://www.concretepage.com/java/jdk-8/lambda-expressions-java-8-
example

http://javarevisited.blogspot.in/2014/01/java-comparator-example-for-custom.html

Hidden features of JAVA-7

Here are some stuff  that I came across so far.

 1.NumberFormatException
int value = 123_8934758;
System.out.println(value);

2.String as argument in Switch condition.

String key1 = "HYD", key2 = "BLR";

Scanner scanner = new Scanner(new InputStreamReader(System.in));
String input = scanner.nextLine();

switch (input) {
case key1:
System.out.println("HYD HERE");
break;
case key1:
System.out.println("BLR HERE");
break;

default:
System.out.println("DEFAULT HERE");
break;
}

3. Diamond operator
When we doesn’t place both sides then no issues and it accepts specified any
type of object like Integer,String,Object etc because by default it will take
Object as generic type.

When we doesn’t place at left side then no issues and it accepts specified any
type of object like Integer,String,Object etc because by default it will take
Object as generic type.

When we place both sides then no issues and it accepts only specified Generic type.

When we place at left side then issues and it accepts only specified any type.

List list = new ArrayList();
List list2 = new ArrayList();
List list3 = new ArrayList();
List list4 = new ArrayList();

List list5 = new ArrayList();
List list6 = new ArrayList();

list5.add(new Long(123));
list5.add(new Integer(548));

list.add("ABC");
list.add(new Object());
list.add(new String("Hey"));
list.add(new Integer(125));

list2.add(new Object());
list2.add(new String("Hey"));
list2.add(new Integer(125));

list3.add(new Object());
list3.add(new String("Hey"));
list3.add(new Integer(125));

list4.add(new Object());
list4.add(new String("Hey"));
list4.add(new Integer(125));

4. Parallel catching of Exceptions:

When all are placed in different exception hierarchies then we can place as this.
NullPointerException | IOException | ArithmeticException | IndexOutOfBoundsException ex

If they fall under same hierarchy then use the base Exception. The below will gives you the CE.

catch (NullPointerException | IOException | ArithmeticException | FileNotFoundException ex) {
ex.printStackTrace();
}

If you are using Checked Exception then it should be thrown.
IOException etc.

try {
File file = new File("C://Demos//me.txt");
FileInputStream fileInputStream = new FileInputStream(file);

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
while (bufferedReader.readLine() != null) {
System.out.println(new SimpleDateFormat("DD/MM/YYYY"));
}
throw new ArithmeticException();
} catch (NullPointerException | IOException | ArithmeticException | IndexOutOfBoundsException ex) {
ex.printStackTrace();
}

5. Try with resource
Internally it uses implements AutoCloseable {

@Override
public void close() throws Exception {
// TODO Auto-generated method stub
System.out.println(“hey java-7 closable”);
}

try (BufferedReader bufferedReader = new BufferedReader(
new FileReader("C:\\Users\\n0290635\\Desktop\\het.txt"))) {
while (bufferedReader.readLine() != null) {
System.out.println(bufferedReader.readLine());
}
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}

try (CustomClass customClass = new CustomClass()) {
customClass.methodNene(123);
} catch (Exception exception) {
exception.printStackTrace();
}

class CustomClass implements AutoCloseable {

@Override
public void close() throws Exception {
// TODO Auto-generated method stub
System.out.println("hey java-7 closable");
}

public void methodNene(int a) {
System.out.println("result:" + a * a * 120);
}

}

6. Rethrow error -Throwing the exception in catch block too.
private static void rethrowErrorJAVA7() throws IOException, Exception {

try {
new SimpleDateFormat("yyyyMMdd").parse("foo");
new FileReader("file.txt").read();
} catch (ArithmeticException arithmeticException) {

} catch (Exception exception) {
throw exception;
}
}

StringBuffer capacity vs ensureCapacity and trimtoSize()

package com.me.practice;

public class StringBufferClass {
public static void main(String[] args) {

//By default it’s 0
StringBuffer stringBuffer=new StringBuffer();

//By default it’s 16
System.out.println(stringBuffer.capacity());

//Now appending “xxxx”
stringBuffer.append(“madhu”);

//Capacity won’t change if length < default capacity
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will change if length > default capacity
stringBuffer.append(“madhugggggggggggggggggggggggg”);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity won’t change if ensureCapacity < current capacity
stringBuffer.ensureCapacity(23);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will change if ensureCapacity > current capacity
stringBuffer.ensureCapacity(123);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will reduce to actual size
stringBuffer.trimToSize();
System.out.println(stringBuffer.capacity());

}
}

 

16
16
5
34
34
34
34
123
34
34

ThreadFactory(I) in JAVA

Here are some notes on ThreadFactory(I):

A Sample Programme:

package com.practice.thread;

import java.awt.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.ThreadFactory;

class LogicThread implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}

}

class ThreadFactoryImpl implements ThreadFactory{
private String threadName;
public ThreadFactoryImpl(String threadName) {
super();
this.threadName = threadName;
this.listThreads = new ArrayList<String>();
}
private int counter=1;
private java.util.List<String> listThreads;

@Override
public Thread newThread(Runnable r) {
// TODO Auto-generated method stub
Thread t = new Thread(r, threadName + “-Thread_” + counter);
counter++;
listThreads.add(String.format(“Created thread %d with name %s on %s \n”, t.getId(), t.getName(), new Date()));
return t;
}

public String getThreadValues(){
StringBuffer stringBuffer=new StringBuffer();
Iterator<String> iterator=listThreads.iterator();
while(iterator.hasNext()){
stringBuffer.append(iterator.next());
}
return stringBuffer.toString();
}
}
public class ThreadFactoryExample {
public static void main(String[] args) {
ThreadFactoryImpl threadFactoryImpl=new ThreadFactoryImpl(“Thread_Factory”);
LogicThread logicThread=new LogicThread();
//Thread logic i.e sleep
Thread thread;
for(int i=0;i<10;i++){
thread=new Thread(logicThread);
thread=threadFactoryImpl.newThread(thread);
//Creating thread using Facoty Impl by using newThread()
thread.start();
}
System.out.println(threadFactoryImpl.getThreadValues());
}
}

 

Created thread 11 with name Thread_Factory-Thread_1 on Sun Jan 22 14:24:17 IST 2017
Created thread 13 with name Thread_Factory-Thread_2 on Sun Jan 22 14:24:17 IST 2017
Created thread 15 with name Thread_Factory-Thread_3 on Sun Jan 22 14:24:17 IST 2017
Created thread 17 with name Thread_Factory-Thread_4 on Sun Jan 22 14:24:17 IST 2017
Created thread 19 with name Thread_Factory-Thread_5 on Sun Jan 22 14:24:17 IST 2017
Created thread 21 with name Thread_Factory-Thread_6 on Sun Jan 22 14:24:17 IST 2017
Created thread 23 with name Thread_Factory-Thread_7 on Sun Jan 22 14:24:17 IST 2017
Created thread 25 with name Thread_Factory-Thread_8 on Sun Jan 22 14:24:17 IST 2017
Created thread 27 with name Thread_Factory-Thread_9 on Sun Jan 22 14:24:17 IST 2017
Created thread 29 with name Thread_Factory-Thread_10 on Sun Jan 22 14:24:17 IST 2017

Thread_Factory-Thread_1
Thread_Factory-Thread_3
Thread_Factory-Thread_2
Thread_Factory-Thread_4
Thread_Factory-Thread_9
Thread_Factory-Thread_5
Thread_Factory-Thread_6
Thread_Factory-Thread_7
Thread_Factory-Thread_8
Thread_Factory-Thread_10

 

HashMap vs TreeMap vs HashTable vs concurrentHashMap values and keys

import java.util.*;
import java.util.concurrent.*;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);

//Key shouldn’t be null in treemap
//If we put two keys similar it will ovverride
//multiple Null values are allowed
TreeMap<String,String> treeMap=new TreeMap<String,String>();
treeMap.put(“null”,null);
treeMap.put(“null1”,null);
treeMap.put(“null”,”nuller”);
treeMap.put(“null2″,null);
System.out.println(treeMap);

//one key can be null
//If we put two keys similar it will ovverride
//Multiple null values allowed
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(null,null);
hashMap.put(null,”null1”);
hashMap.put(“null1”,null);
hashMap.put(“null2”,null);
hashMap.put(“null3″,null);
hashMap.put(null,”nuller”);
System.out.println(hashMap);

//No nulls as keys as well as values too
Hashtable<String,String> hashTable=new Hashtable<String,String>();
hashTable.put(“null”,”null-1″);
hashTable.put(“null1″,”null”);
hashTable.put(“null1″,”nuller”);
System.out.println(hashTable);

//No nulls as keys as well as values too
//thread safe
Map<String,String> conMap= new ConcurrentHashMap<String,String>();
conMap.put(“null1″,”null”);
conMap.put(“null”,”nuller”);
System.out.println(conMap);
}
}

 

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null3=null, null1=null, null2=null}
{null=null-1, null1=nuller}
{null=nuller, null1=null}

If we put null as key in treemap or hashtable or concurrentHastable then it won’t  throws any  error at Compile Time.but it will throw below error at runtime

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
2147483647
-2147483648
7b
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null3=null, null1=null, null2=null}
Exception in thread “main” java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:464)
at StaticVsNormalVsNo_Imports.main(StaticVsNormalVsNo_Imports.java:44)

Static vs Normal vs No imports in JAVA

Why imports are useful:

An import declaration allows a static member or a named type to be referred to by a simple name that consists of a single identifier. Without the use of an appropriate import declaration, the only way to refer to a type declared in another package, or a static member of another type, is to use a fully qualified name.

A single-type-import declaration imports a single named type, by mentioning its canonical name.

A type-import-on-demand declaration imports all the accessible types of a named type or package as needed. It is a compile time error to import a type from the unnamed package.

A single static import declaration imports all accessible static members with a given name from a type, by giving its canonical name.

A static-import-on-demand declaration imports all accessible static members of a named type as needed.

http://stackoverflow.com/questions/2903166/meaning-of-the-import-statement-in-a-java-file

What happen if we don’t declare imports in JAVA file:

The below program I am trying to call one of the method add of Arraylist i.e java.util.Arraylist i.e https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(E) .As i didn’t declared any imports in my .java file it throws error like below.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
Arraylist arraylist=new Arraylist();
System.out.println(arraylist.add());
}
}

o/p:
D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java
StaticVsNormalVsNo_Imports.java:4: error: cannot find symbol
System.out.println(arraylist.add());
^
symbol: method add()
location: variable arraylist of type Arraylist
1 error

If we try to  get rid of the error by doing some changes like creating my own Arraylist class as below.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
Arraylist arraylist=new Arraylist();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

class Arraylist{
public String add(int a){
return “Mehtod message……..”+a;
}
}

o/p:
D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
Mehtod message……..10
Arraylist@15db9742

But it is not the functionality what i intended to do  so I move one step forward and I am giving here the fully qualified name i.e java.util.Arraylist<E>.

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
java.util.ArrayList<Integer> arraylist=new java.util.ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

class Arraylist{
public String add(int a){
return “Mehtod message……..”+a;
}
}

o/p:
D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]

Now functionality is working as expected ,but what if i want’s to use 100 or 10 arraylists.In this case writing of java.util.ArrayList<Integer> arraylist=new java.util.ArrayList<Integer>(); 100 times or 10 times doesn’t make sense.So here java people import statement to rescue.

import java.util.ArrayList;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new .ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);
}
}

o/p:

true [10]

What import java.util.ArrayList saying is whenever compiler sees the word ArrayList in the class it will use the java.util.ArrayList i.e in the JAVA API document there is a package called util and in that package there is class called ArrayList.

Here A package may contains many number of classes if i want to use one or more classes in a perticular package ,We are having an option wildcard character(*).If compiler sees the * symobol in import declaration it will search for all the classes in the entire package.

import java.util.*;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);

//Key shouldn’t be null in treemap
//If we put two keys similar it will ovverride
//multiple Null values are allowed
TreeMap<String,String> treeMap=new TreeMap<String,String>();
treeMap.put(“null”,null);
treeMap.put(“null1”,null);
treeMap.put(“null”,”nuller”);
treeMap.put(“null2″,null);
System.out.println(treeMap);

//one key can be null
//If we put two keys similar it will ovverride
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(null,null);
hashMap.put(null,”null1”);
hashMap.put(“null1”,null);
hashMap.put(“null2″,null);
hashMap.put(null,”nuller”);
System.out.println(hashMap);

//No nulls as keys as well as values too
Hashtable<String,String> hashTable=new Hashtable<String,String>();
hashTable.put(“null”,”null-1″);
hashTable.put(“null1″,”null”);
hashTable.put(“null1″,”nuller”);
System.out.println(hashTable);

}
}

o/p:

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null1=null, null2=null}
{null=null-1, null1=nuller}

static imports in JAVA:

If we want to access the static members and methods of a class with out using the classname evrytime i.e Classname.XXXXX etc.Here is the example

System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.toHexString(123));

instead of putting class name every time we will go for static import.

import java.util.*;
import java.util.concurrent.*;

import static java.lang.System.out;
import static java.lang.Integer.*;
//static import won’t work
public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
out.println(MAX_VALUE);
out.println(MIN_VALUE);
out.println(toHexString(123));

o/p:

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
2147483647
-2147483648
7b

but it is having dis advantage like

  • readability
  • both Long and Integer having MAX_VALUE etc similar properties in this case if we put wild card import(*)  it leads us to Compile Time Error.

Creating object(s) for class,interface,Abstract class,final class and enum in JAVA.

In java every communication among the classes merely done by the methods with the help of objects.The below link shows the various advantages with object in java.

Advantages with Object:

  • Define the structure and behavior of a class.
  • Independence-i.e One object values doesn’t affects the other object values.
  • Modularity- Once it got created ,We can move the object over methods or any where in the program.

Bundling code into individual software objects provides a number of benefits, including:

  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  2. Information-hiding: By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

WHY WE NEED OBJECT IN JAVA….? 

Creating a object for Class:

  • There are numerous ways to create an object for a particular class in java.But here i am showing only the most generalized way i.e using new keyword.

class Demo{
public String string;
//Definfing the structure of class
public Demo(String str){
this.string=str;
System.out.println(“In construcor”+string);
}
//Here we are changing the behabiour of class through method
public String getName(){
return “Brad Pitt”;
}
}
public class Demo_Object{
public static void main(String[] args)throws Exception{
//creating the object with new() operator
Demo demoObject=new Demo(” Mr..”);
String str=demoObject.getName();
System.out.println(str);
}
}

o/p:
D:\OCJP>javac Demo_Object.java

D:\OCJP>java Demo_Object
In construcor Mr..
Brad Pitt

 

Creating Object for an interface:

As all of us knew that interface is a kind of class but the only difference we see is abstraction i.e interface is 100% abstract.Directly we can’t create object for interface.Why so,Here are nice explanations

https://www.quora.com/Why-cant-we-create-an-object-to-interface-in-Java

http://softwareengineering.stackexchange.com/questions/263301/i-want-to-understand-clearly-why-cant-we-instantiate-an-object-of-an-abstract-c

But through Anonymous classes we can create the objects.Example programs are below.

interface TestInterface{
String toString();
}

public class Object_Creation3{
public static void main(String[] args)throws Exception{
System.out.println(new TestInterface(){
public String toString(){
return “HAAAAAAAAAAAhhhaaaaaaa”+this.getClass();
}
});
}
}

o/p:

D:\OCJP>javac Object_Creation3.java

D:\OCJP>java Object_Creation3
HAAAAAAAAAAAhhhaaaaaaaclass Object_Creation3$1

 

With that syntax, you create an anonymous class, which is perfectly legal.

Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class’ name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:

 

Object Creation for Abstract class:

We can’t create for object for an Abstract class because if we do also the implementation must happen i.e through extends otherwise it will left remains as an empty template.

Because it’s abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.

Take for example an “Animal” abstract class. There’s no such thing as a “pure” animal – there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn’t be able to instantiate plain Animal – that’s just a basic template. And there’s certain functionality that all animals share, such as “makeSound()", but that can’t be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?

 

abstract class AbstractClassSample{
public String name;
//public AbstractClassSample(String name){
//this.name=name;
//}
public abstract void getName();
public String getCompany(){
return “OpenText”;
}
}

public class Abstract_ObjectCreation{
public static void main(String[] args)throws Exception{
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar pichai”);
System.out.println(abstractClassSample.getCompany());
}
}

o/p:

D:\OCJP>javac Abstract_ObjectCreation.java
Abstract_ObjectCreation.java:14: error: AbstractClassSample is abstract; cannot
be instantiated
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar picha
i”);
^
1 error

But we can get benefit with inheritance in the case of Abstract class by extending the abstract class to sub class and creating object for sub class as below.

abstract class AbstractClassSample{
public String designation=”Software Engineer”;
public AbstractClassSample(String d){
this.designation=d;
}
public abstract String getName();
public String getCompany(){
return “OpenText”;
}
}

class Abstract_Inheritence extends AbstractClassSample{
public int employeeId;
public Abstract_Inheritence(int no,String d){
super(d);
this.employeeId=no;
}
public String getName(){
return “Madhu”;
}
//public String getCompany(){
// return “PegaSystems”;
// }
}

public class Test_Inhiritence{
public static void main(String[] args)throws Exception{
Abstract_Inheritence abstract_Inheritence=new Abstract_Inheritence(123,”Associate”);
String s1=abstract_Inheritence.getName();
String s2=abstract_Inheritence.getCompany();
System.out.println(s1);
System.out.println(s2);
}
}

o/p:

D:\OCJP>javac Test_Inhiritence.java

D:\OCJP>java Test_Inhiritence
Madhu
OpenText

 

 

Object Creation for final class:

We can create object for a final class as normal i.e first use case.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
}
}

o/p:
D:\OCJP>javac FinalClassObject.java

D:\OCJP>java FinalClassObject
In ConstructorMr.Ramanjan

But final class cannot be extended .It will throgh the error as below.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject extends Final_Demo{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
System.out.println(“errorr……”);
}
}

o/p:

D:\OCJP>javac FinalClassObject.java
FinalClassObject.java:7: error: cannot inherit from final Final_Demo
public class FinalClassObject extends Final_Demo{
^
FinalClassObject.java:7: error: constructor Final_Demo in class Final_Demo canno
t be applied to given types;
public class FinalClassObject extends Final_Demo{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
2 errors

Creating Object for enum:

Enums cannot be intialized as they only a private constructor.

public enum Sample{
   READ,WRITE
}   


//Will get convetred the above code into below internally.


class Sample extends Enum {
    public static final Sample READ = new Sample("READ", 0);
    public static final Sample WRITE = new Sample("WRITE", 1);

    private Sample(String s, int i)
    {
        super(s, i);
    }

    // More methods, e.g. getter
}

Is Java is case-sensitive language?

YES…yes

Look at below snippet.

public class Main_Demo{
public static void main(String[] args)throws Exception{
System.out.println(“Keep Challenging………….”);
System.out.println(“Building tomorrow’s enterprise………….”);
String name=”cognizant”;
String NAME=”Infosys”;
System.out.println(name);
System.out.println(NAME);
}
}

 

D:\OCJP>javac Main_Demo.java

D:\OCJP>java Main_Demo
Keep Challenging………….
Building tomorrow’s enterprise………….
cognizant
Infosys

D:\OCJP>

Though both having same name as name because of the feature of case sensitiveness. It takes as two different strings.

Even if i compile with case it won’t work.

D:\OCJP>javac Main_Demo.java

D:\OCJP>java MAIN_DEMO
Error: Could not find or load main class MAIN_DEMO

D:\OCJP>java main_demo
Error: Could not find or load main class main_demo

D:\OCJP>Main_Demo
‘Main_Demo’ is not recognized as an internal or external command,
operable program or batch file.

D:\OCJP>java Main_Demo
Keep Challenging………….

Case sensitive  and case- insensitive Languages:

https://en.wikipedia.org/wiki/Case_sensitivity

Some computer languages are case-sensitive for their identifiers (C, C++, Java, C#, Verilog,[1] Ruby[2] and XML). Others are case-insensitive (i.e., not case-sensitive), such as Ada, most BASICs (an exception being BBC BASIC), Fortran, SQL[3] and Pascal.