Menu

Showing posts with label Java Learning. Show all posts
Showing posts with label Java Learning. Show all posts

package javax.annotation does not exist

Error package javax.annotation does not exist; this means that configured JDK is not working properly or there is some conflict in installed JDK version.

If you are using any IDE tool for development and experienced this error, then go to project build path and check the right JDK is configured in the build path.[Please refer our post How to configure build path and JDK for project]. We may also face this error when we have multiple JDK installed in our machine. So add the correct JDK library for project, then clean the project and build again.

Hope this will help you and fix your issue.

New Features in JAVA10

JAVA 10 NEW FEATURES

1. Local Variable Type Inference
2. Time-Based Release Versioning
3. Garbage-Collector Interface
4. Parallel Full GC for G1
5. Heap Allocation on Alternative Memory Devices
6. Consolidate the JDK Forest into a Single Repository
7. Root Certificates
8. Experimental Java-Based JIT Compiler
9. Thread-Local Handshakes
10. Remove the Native-Header Generation Tool


Oracle Java 10
 

Environment variable What, Why, Where and How?

What is environment variable?

Environment variable is variable which holds the path of the software installed in your machine.

Why do we need to set environment variable?

When we compile and run any program, then machine try to find the required compiler or runtime to perform the action which we have requested. So either we to have to specify the directory of the software library every time with our command or we could set it into an environment variable so machine can automatically pickup the library path from there based on the command.
For example:
We set python variable to compile and execute the Python code.
python = C:\Python\Python27\python.exe
We set the JAVA_HOME for compile and run the Java programs.
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_201 
We set MVN_HOME for maven build.
MVN_HOME = D:\apache-maven-3.6.0\bin 

Instead of creating all these variable we could also just add these library paths in a common user variable PATH and later add PATH variable in system variable CLASSPATH.

How to set environment variable?

Right click on my computer icon and select the properties option.

A new window will be get opened. Now click on the advance system settings
advance-system-settings-environment-variable
advance-system-settings-environment-variable

Now click on the environment variables button.
environment-variables
environment-variables
Now here you could either add the installed library path under the PATH user variable to you could create a new user variable and later add the newly create variable in CLASSPATH system variable.
environment-variable-paths.JPG
environment-variable-paths.JPG

How to swap two variable without using temporary variable in java?

Swap two integer variable a and b without using any temporary variable.
Set the initial value for two variable and then swap the value from a to b and b to a. Below is the code snippet written in Java programming to swap two variable without using third variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package jorvee;

public class SwapTwoIntegerVariableWithoutUsingTheThirdVariable {

 public static void main(String[] args) {
  int a=5, b=3;
  System.out.println("Before swap value of a: "+a +" and value of b: "+b);
  a = a*b;
  b = a/b;
  a = a/b;
  System.out.println("After swap value of a: "+a +" and value of b: "+b);
 }
}

Output:

Before swap value of a: 5 and value of b: 3
After swap value of a: 3 and value of b: 5

Another approach to do the same. Swap two variable without using third variable

How to swap two Integer variables without using the third variable?

Swap two integer variable a and b without using any temporary variable.
Set the initial value for two variable and then swap the value from a to b and b to a. Below is the code snippet written in Java programming to swap two variable without using third variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package jorvee;

public class SwapTwoIntegerVariableWithoutUsingTheThirdVariable {

 public static void main(String[] args) {
  int a=5, b=3;
  System.out.println("Before swap value of a: "+a +" and value of b: "+b);
  a = a+b;
  b = a-b;
  a = a-b;
  System.out.println("After swap value of a: "+a +" and value of b: "+b);
 }
}

Output:

Before swap value of a: 5 and value of b: 3
After swap value of a: 3 and value of b: 5

Another approach to do the same. Swap two variable without using third variable 

How to swap two String variables without using the third variable?

We are going to see how to swap two variable of type String without using any third or temporary variable. 
This is very frequent question asked by interviewer in any Java technical interview.

Below is a simple java program to swap two String variables a and b.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package jorvee;

public class SwapTwoStringVariableWithoutUsingTheThirdVariable {

 public static void main(String[] args) {
  String a="swap", b="two numbers";
  a= a+b;
  b= a.substring(0, a.length() - b.length());
  a= a.substring(b.length());
  System.out.println("After swaping value of a is: "+a);
  System.out.println("After swaping value of b is: "+b);

 }

}

Output:

After swaping value of a is: two numbers
After swaping value of b is: swap

Find minimum and maximum number from a given array

This is an example code snippet to find the minimum and maximum number in a given Array using Java programming. 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import java.util.Scanner;

public class FindMinMaxInArray {

    public static void main(String[] args) {
        int nums[]=new int[]{3, 5, 6, 2, 4, 15, 120};
        int max = 0, min= 0;
        max = min = nums[0]; 
        for (int i = 1; i < nums.length; i++) {
            if(nums[i]>max) max = nums[i];
            if(nums[i]<min) min = nums[i];
        }
        System.out.println("Minimum number is "+min + "\nMaximum number is "+max);
       
    }
}

Output:

Minimum number is 2
Maximum number is 120

Related articles:

Convert date-time from 12 to 24 hours of format

Today we are going to see, how we can convert a 12 hour time format into 24 hour(military) time format.
For example we have date like 12 Aug, 2018 07:05 PM or 04/03/1965 02:06:45 AM or just only have time 07:15:00 AM or 08:50:25 PM which we want to convert in 24 hours format and remove the AM and PM from the date.

Here I have written a simple program which help us to understand the process and what steps do we need to perform to convert a string time into 24 hours of time format. 
Below are the code snippet.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package jorvee;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class timeFormet {

 public static void main(String[] args) throws ParseException {
  String time="07:05:45 PM";
  /*
   * This dateFormat will help you to first convert your string time into DateTime format.
   */
  DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss aa");
  Date date24=dateFormat.parse(time);
  /*
   * Convert your time into 24 hours date format
   */
  DateFormat outFormat = new SimpleDateFormat( "HH:mm:ss");
  System.out.println(outFormat.format(date24));

 }
}

Output:

19:05:45

Recursive method in Java

How to write a recursive method in Java?

Below is the code snippet of a recursive method in Java to generate numbers and check the number and execute the method again. In the below example printNumber() is a recursive method that will get called inside its own body.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package rashidjorvee;

public class RecursiveMethod {

 public static void main(String[] args) {

  RecursiveMethod recursiveMethod=new RecursiveMethod();
  recursiveMethod.printNumber(2);

 }
 private void printNumber(int j) {
  try {
   int i=j; 
    if(i==2) {
     printNumber(4);
    }
    System.out.println("Number "+i);
    }
  catch(Exception e) {

  }
 }
}

How to run a Java Application or program without main method?

Below is the code snippet to execute and run a java program without main method.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package rashid.jorvee;

import javafx.stage.Stage;

public class RunAJavaApplicationWithoutMainMethod extends javafx.application.Application {
 
 @Override
 public void start(Stage primaryStage) throws Exception {
  System.out.println("Running Application!!!");
 }
}

trimToSize() in Java

trimToSize() method used to reduce the capacity of the ArrayList, StringBuffer and StringBuilder in Java. Trims the capacity of the instance(ArrayList, StringBuffer and StringBuilder) to be the list's current size. An application can use this operation to minimize the storage of those instances.
Let understand this method using a scenario, for example, we have created a StringBuffer and assign some value into it. suppose we have put "trim to size method in java" string into it. And when you will pull the length of the StringBuffer then it will return the actual size of the string, which, we have assign into it, in our case, it will return 27. But when you will fetch the capacity if the StringBuffer then it will give you output more than the length of StringBuffer, in our case it is returning 34. This means this Buffer has more capacity and could store more data into it. Since our text has the length of 27, and we don't want that extra capacity anymore in our instance then we could remove and free the extra capacity from that instance using trimToSize method. And this method will trim the capacity of an instance with the size or length of the instance.  

Here is an example code of trimToSize() method with StringBuffer

Output:
trim to size method in java, and length of StringBuffer copyText is:27
Capacity of copyText is::34
trim to size method in java, and length of StringBuffer copyText after trimToSize() is:27
Capacity of copyText after trimToSize() is::27

How to iterate on a JSON objects using Java

Today we are going to see how to iterate on a JSON object or read a JSON file and fetch key and value from that JSON file using Java.

Below is the example code snippet.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package rashidjorvee;

import java.io.FileReader;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonReader {
 /* JSON data file
  * [
    {
      "componentName": "comp1""compKey": [
        {
          "keyname": "json_key1",
          "props": [
            {
              "fieldLabel": "Jorvee",
              "name": "./productProperty",
              "id": "productID",
              "sling:resourceType": "granite/ui/components/foundation/form/textfield"
            }
          ]
        }
      ]
    },
    {
      "componentName": "comp2""compKey": [
        {
          "keyname": "json_key2",
          "props": [
            {
              "fieldLabel": "Rashid",
              "name": "./productProperty",
              "id": "productID",
              "sling:resourceType": "foundation/components/parsys"
            }
          ]
        }
      ]
    }
  ]
  */
 public static void main(String[] args) {
  try{
   JSONParser parser=new JSONParser();
   JSONArray a = (JSONArray) parser.parse(new FileReader("D:\\json/jsonFile.json"));
   for (Object comp:a) {
    JSONObject key1 = (JSONObject) comp;
    String componentName = (String) key1.get("componentName");
    System.out.println("componentName: "+componentName);
    JSONArray compkeys = (JSONArray) key1.get("compKey");
    for (Object o : compkeys)
    {
     JSONObject key = (JSONObject) o;
     String keyName = (String) key.get("keyname");
     System.out.println("KeyName: "+keyName);
     
     JSONArray keys = (JSONArray) key.get("props");
     for (Object prop : keys) {
      JSONObject properties = (JSONObject) prop;
      
      String name = (String) properties.get("name");
      System.out.println("Name: " +name);
      
      String fieldLabel = (String) properties.get("fieldLabel");
      System.out.println("City: "+fieldLabel);
      
      String job = (String) properties.get("sling:resourceType");
      System.out.println("resourceType: "+job);
      
      String id = (String) properties.get("id");
      System.out.println("ID: "+id);
      
     }
     System.out.println("\n");
    }
   }
  } catch(Exception e) {}

 }

}

How to store multiple values for a key into Map using JAVA

Today we will practice a program to assign or set multiple values or list of values or ArrayList for a key in Map. And also how to iterate on that map and find the value from the list of values.

Declare a Map, with a string or integer key and list or ArrayList type of value; as given in below code in line 10. In this Map, you can store a single value as a key and a list of values you could store into that key in form of a list or array list.
Line 10: Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
In line 12 we are creating an ArrayList in which we will store the list of values and we will put this list into Map.
Line 12: ArrayList<String> list = new ArrayList<String>();
Later in line 13 and 14, we are adding values in ArrayList.
Line 13 and 14: list.add("A"+i);
                          list.add("B"+i);
On top of this ArrayList we have created a for loop which will help us to create the pair of 10 unique values of key and value and mapped and put those values into the map.

Line 15 of the code is to put a pair of key and value into a map.
Line 15: map.put("index"+i, list);
We have completed the creation of map. Now we will see how to iterate through the map and pull a particular key or value. or how to find a value into map? or how to find a matching value from a list stored into a map?
To iterate on map first we have to create an object of Entry class with the help of Map and entrySet(). Below is the foreach loop using that we can iterate on all keys of the map.  
Line 19: for(Map.Entry<String, ArrayList<String>> entry : map.entrySet())
Now using the entry object we can pull the key and values of the current iteration index. Below are the codes to getKey() and getValue() from the map. Line 20 of the code will return the value stored as a key, and line 21 will return a list of values stored into the value of the map of the current index.
Line 20: String key = entry.getKey();Line 21: ArrayList<String> value = entry.getValue();
To find a value from map or the list of values stored into the map we will use the matches() method and using regex we could find the matching values at the specified index. In line 23 of the code, we are searching a value B5 which we have stored in the list of values. If we have a list of values then we have to specify the index number using get(index) in which method matches() will search for the requested value.
Line 23: if(entry.getValue().get(1).matches("B5")) 
To search a value from simple key-value pairs of map then we could simply write the above line without get() method. e.g. if(entry.getValue().matches("B5")) and in similar way you could find a key as well. e.g. if(entry.getKey().matches("index7"))

Below is the complete example code which you could directly copy and paste in your IDE and practice this exercise.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package rashidjorvee;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MultipleValuesInMap {

 public static void main(String[] args) {
  Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
  for(int i=1; i<=10; i++) {
   ArrayList<String> list = new ArrayList<String>();
   list.add("A"+i);
   list.add("B"+i);
   map.put("index"+i, list);
  }

  System.out.println(map);
  for(Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
   String key = entry.getKey();
   ArrayList<String> value = entry.getValue();
   //System.out.println(value.get(1).matches("(?i)b2|B3|B4"));
   if(entry.getValue().get(1).matches("B5")) {
    System.out.println(entry.getKey() +" " +entry.getValue().get(0) +" " +entry.getValue().get(1));
   }
  }
  System.out.println(map.size());

 }

}

Error: Could not find or load main class

If you are getting the error Error: Could not find or load main class when you try to run any java program in using eclipse then you could perform any of the following resolutions to fix the issue. If a single resolution doesn't work for you then perform the next solution which is given below.

1. Go to your project path for e.g. C:\Users\java\rashid\jorvee > open .classpath file and verify all the entries given in this file are actually exist in your system. Below is the sample file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>

<classpath>

 <classpathentry exported="true" kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>

 <classpathentry kind="src" path="src"/>

 <classpathentry exported="true" kind="lib" path="C:/Users/java/rashid/java-json.jar/java-json.jar"/>

 <classpathentry kind="output" path="bin"/>

</classpath>

2. Go to run > run configuration > classpath> Select Project > Advance > select option add folder and select the bin folder where your .class file get stored.

3. There might be a possibility that there is no classpath set for java class files. Please go ahead and set classpath manually by executing the below command on cmd.
javac -cp . PackageName/*.java

4. In some cases we have found that Java build path is not set up for the project, or somehow it gets removed from the directory then go ahead and set your project classpath here. Add your project in the source tab and JRE in libraries tab.
Project > Properties > Java Build Path

Eclipse shortcuts for Java programming

When you are working with Eclipse IDE to write the java programs, we have too many shortcuts to write the statements in java which Eclipse supports. using these shortcuts you could write your program easy and fast. 
Here I am writing few shortcuts to write java program in Eclipse IDE. Go and try these shortcuts and let us know you have other shortcuts to write and make efficient programming.

Shortcuts commands:

  1. ALT + CTRL + A: to edit and write multiple lines simultaneously  
  2. ALT + Shift + J: Add code Definition
  3. Select a line then ALT + Arrow (Up/Down): to move the code up and down
  4. Shift + Alt + I: to align the code
  5. Shift + mouse hover: to see the method implementation code.
  6. CTRL + O: to see the list of all variables and methods.
  7. CTRL + K: to find matching text within the file.
  8. CTRL + Click on a method name to open the implementation of the method.
  9. Ctrl + space: to open the preference window or template proposal.
  10. You can directly copy and paste your complete code from notepad to eclipse SCR folder, and eclipse will automatically create package and class for that class and paste your code into it. Open notepad > Copy all code from pad > open eclipse > right click on src folder in case if you don't have src folder then right click on project name > select the paste option 
  11. Inline and split variables: select variable then CTRL + 1 and select the option
  12. CTRL + 2, L to assign the value into a local variable
  13. ALT + Shift + M: Select single or multiple lines and move those selected codes in a new method.
  14. Ctrl + Alt-J: to Join more than one lines in a single line
  15. syserr or sysout: to write the complete System.err.println() or  System.out.println() respectively.
  16. Type a string literal "rashid"; select the literal "rashid", then press Ctrl + space, now type sysout/syserr to to pass that string in the argument.


If you face any issue in using these shortcuts then please let us know, we will help you to understand these shorthands.

Pass by reference and pass by value in Java

Today in this tutorial of Java program we will see how to work with pass by value and pass by reference. 

Below is code snippet.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

package com.rashid.jorvee;


public class ValueRef {

 public static void main(String[] args) {

  Employee emp=new Employee();

  ValueRef valref=new ValueRef();

  emp.setSalary(12000.00);

  System.out.println("Employee emp salary: " +emp.getSalary());

  valref.salary(emp);

 }

 public void salary(Employee em){

  em.setSalary(14000.00);

  em=new Employee();

  em.setSalary(15000.0);

  System.out.println("Employee em salary: " +em.getSalary());

 }

}



class Employee{

 double salary;

 public double getSalary() {

  return salary;

 }


 public void setSalary(double salary) {

  this.salary = salary;

 }
}

Output:
Employee emp salary: 12000.0
Employee em salary: 15000.0 

Working with list and arrayList in Java.

In this tutorial we will see a simple and small implementation of List and ArrayList using Java.

ArrayList is resize-able implementation is List type. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

We are writing a program where we will add some values in the ArrayList and then we will iterate on that List and print the values on console.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package rashid.jorvee;

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

public class ListImpl {

 public static void main(String[] args) {
  List list=new ArrayList();
  List newlist=new ArrayList();
  newlist.add("New Delhi");
  newlist.add("9999999");
  newlist.add("1212121");
  newlist.add("Rashid");
  newlist.add("Jorvee");
  for(int i=0;i<newlist.size();i++) {
   System.out.println("At Index "+i +" List has value "+newlist.get(i));
  }

 }

}
Output:
At Index 0 List has value New Delhi
At Index 1 List has value 9999999
At Index 2 List has value 1212121
At Index 3 List has value Rashid
At Index 4 List has value Jorvee

Import and Export Java project in a Zip file in Eclipse

Importing a Java Project from a Zip File into a Workspace

In the past, we have imported projects as JAR files into the src folder of an existing project. For this course, it will probably be easier to import projects directly into the workspace. This is especially true with shader programs since they often require additional text file resources (in our case, shader source code in simple text files) that we didn’t encounter in previous Java programs. When I create demo projects for you, I will often create them for you as zip files.

To import a Java project from a zip file into a workspace:

1. Open Eclipse and navigate to the workspace. To make life easier for us all, make that the workspace that includes your other JOGL projects.
2. Select File…Import…
3. Expand General, select Existing Projects into Workspace and click Next.
4. Click the Select archive file radio button and browse for the zip file containing the project.
5. Click Finish and the project should appear in your workspace. Note: Eclipse will not import a project if you already have one with the same name. If you still want to proceed, rename the existing one and try importing again.

Exporting a Java Project to a Zip File

If you want to export one of your projects to a zip file, do this:

1. Left-click the project name in Package Explorer that you want to export (For example, if the project is named ColorMixer, left-click on that name).
2. Select File…Export…
3. Expand General, select Archive File, and click Next.
4. In the Export dialog, make sure that your selected project is checked and that the options Save in zip format and Create directory structure for files are both selected.
5. Browse for a location to save the archive file. A zip extension will be added automatically.
6. Click Finish and your project should be saved as a zip file in the location you requested.

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

If you are getting error "No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?" while compiling any java application either using Eclipse, NetBeans and any other IDE, the simple meaning of this error is; you are trying to compile your Java program using JRE which is not possible. To compile any Java program we need JDK.

There could be two reasons which causing this error. Will see both the ways to fix this issue.

How to check installed version of Java in your machine.

1. If you don't have JDK installed in your machine/Computer.

  • To resolve this you need to download the latest version of JDK and install it in your machine. 
  • Then setup environment  variable and path. for more check here.


2. If JDK is already installed in your machine but installed JRE path is not setup to JDK path. 

  • Open eclipse
  • Go to Window > Preferences > Java > Installed JREs > and check your installed JREs.
  • There should be a entry available for JDK in installed JRE. In case there is no JDK entry then you have to add path of installed JDK from your machine.

To do this:
  • Go to C drive of your computer and find the directory of JDK in program files. e. g. C:\Program Files\Java\jdk1.8.0_111 
  • Copy this path and add this path in your installed JREs option in your IDE.
inatalled JRE in eclipse
Inatalled JRE in eclipse
  •  Click on Add button from right side of window. A new window will appear, click on standard VM > Next > In JRE home section put the path of installed JDK from program files and click on finish.
JRE defination window
JRE defination window

  • After doing these all JDK will be appear in your installed JREs window. From there you mark/check JDK and apply.
inatalled JRE in eclipse
Inatalled JRE in eclipse