Tag Archives: java

Solution to the problem of Java program “resource leak: ‘SC’ is never closed” in vscode

Recently I am learning java programming. The configuration of installation and environment variables will be described in detail in the following blog. This blog mainly introduces the warning of “Resource leak:’sc’ is never closed” in java input.

The test code is as follows.

import java.util.*;
public class Print {
    public static void main(String[] args) {
        double num=0;;
        Scanner sc=new Scanner(System.in);
        num = sc.nextDouble();
        if(num == 1){
            System.out.println("1");
        }
        else{
            System.out.println("0");
        }
    }
}

Warning: resource leak:’sc’ will never be closed.

This may bring some security problems, so how to solve this problem? Since’sc’ is not closed, then we only need to close’sc’. At this time, we need to add’sc.close();’ to the end to solve it.

The modified code is as follows.

import java.util.*;
public class Print {
    public static void main(String[] args) {
        double num=0;;
        Scanner sc=new Scanner(System.in);
        num = sc.nextDouble();
        sc.close();
        if(num == 1){
            System.out.println("1");
        }
        else{
            System.out.println("0");
        }
     }
 }

 

JAVA set to determine the null: List.isEmpty() & null == List && List.size()==0

Collection is often used in development (take list as an example). It will be judged to be empty before processing. If it is empty, it will not continue. There are two ways to write it

First of all

List<String> listA = new ArrayList<>();
if(listA.isEmpty()){
	System.out.println(listA);		
}

The second is that

		List<String> listB = null;
		if(null != listB && listB.size() == 0){
			System.out.println(listB);
		}else{
			System.out.println("listB is NULL");
		}

Check the isempty() method source code of ArrayList

As you can see, lista.Isempty() is just looking at the size of the collection, null= Listb is to determine whether the set is null and allocate memory for it

Therefore, it is suggested that when it is not clear whether the set is null, the second method should be used to judge whether the set is empty

How to Solve JAVA Error: “error: bad operand types for binary operator ”

When doing this topic today (142. O (1) check power of 2), I encountered an error “bad operate types for binary operator ‘& amp;”

First, paste the code:

public class Solution {
    /**
     * @param n: An integer
     * @return: True or false
     */
    public boolean checkPowerOf2(int n) {
        // write your code here
         if(n<=0)
           return false;
         return (n&(n-1)==0)?true:false;
    }
}

Error:

At first, I guessed that it was an operator problem, but I also ruled it out. I always feel that there is something wrong with the “true” and “false” behind, but I can’t find it. Later, I learned that it was really a matter of priority, which might be affected by the assignment (=) operator; The priority of “=” is higher than “=”, which is actually the opposite. The identity operator takes precedence over the bitwise operator, which results in “& amp;” The left is int type, the right is boolean type, sure enough, the basic things still can’t be ignored

So just put “return (n & amp( n-1)==0)? true:false; ” Change to “return ((n & amp( n-1))==0)? true:false; ” That’s it

 

JAVA Command Error: A JNI error has occurred, please check your installation and try again [Solved]

Run Java program, javac run. Java file does not report an error, but when Java runs, it reports an error

Look at the error report carefully

Exception in thread “main” java.lang.UnsupportedClassVersionError: helloworld has been compiled by a more recent version of the Java Runtime (class file version 54.0), this version of the Java Runtime only recognizes class file versions up to 52.0

Check the reason and find that it is caused by the inconsistency between Java and javac versions

Java – version and javac – version, if so

The two versions are inconsistent

 

Solution:

1. How many Java versions are there in Linux system

rpm -qa |grep java

2. Then delete them one by one

rpm -e --nodeps java-1.8.0-openjdk-headless-1.8.0.181-3.b13.el7_5.x86_64
rpm -e --nodeps java-1.7.0-openjdk-1.7.0.171-2.6.13.0.el7_4.x86_64
rpm -e --nodeps java-1.7.0-openjdk-headless-1.7.0.171-2.6.13.0.el7_4.x86_64
rpm -e --nodeps java-1.8.0-openjdk-1.8.0.181-3.b13.el7_5.x86_64 
(type rpm -e --nodeps + "existing java version") Delete as many as you can

3. Check whether the original java version is removed completely

[root@yuan 8-1]# java - version
-bash: /usr/bin/java: No such file or directory

4. After the original version is removed, configure the newly installed Java environment variables

vi /etc/profile 

Edit the profile file and add

JAVA_HOME=/usr/local/java/jdk-10.0.2/   ###("jdk-10.0.2" to the installation file name of the version of java you want to install)
JRE_HOME=$JAVA_HOME/ ### (since there is no jre folder after jdk10 is unzipped, if it is for a version below jdk10 it should
                               for “JRE_HOME=$JAVA_HOME/jre”)
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin:$PATH
CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib:$CLASSPATH
export JAVA_HOME JRE_HOME PATH CLASSPATH

5. Last update

source /etc/profile

Complete

The problem of user.home environment variable in Java

Open source software supply chain lighting plan, waiting for you>>>

In the afternoon, several “weird” problems occurred in the process of development

first, when developing in idea, java.util.map class in JDK cannot be imported automatically. Java. Util. Map is not found in the list of auto prompts through online search, it is found that many people have encountered such problems. But the solutions are different. Some people mentioned the problem of JDK version conflict
using everything to search java.exe on my PC, I found that there were multiple versions of java.exe. When I located to the idea, I started it with jdk8, while the JDK configured in the development project was 1.7

after trying to uninstall jdk8, restart idea and prompt to select setting directory (i.e. idea directory).
select the. Idea directory under the current user directory in windows and start OK
when you enter map in the edit, you can automatically prompt java.util.map, which seems to be the problem of JDK version conflict I think I can finally develop it happily, and I feel very happy

a more “weird” problem followed
before compiling OK projects, all of them were prompted with mutation errors, and no third-party jars could be found
these jars are all in the Maven image library of the company. What the hell is this NIMA?It’s an unpleasant job
Ctrl + Alt + s open the configuration dialog box of idea, locate Maven in build tools, and find the problem

a

The default settings.xml file used by Maven points to D:// documents \. M2 \ \ settings.xml, and the default repository also points to D:// documents \. M2 \ \ repository. We found the problem. Previously, we used the settings.xml in the root directory of the current user in windows, and the central repository configured here uses the internal image of the company, However, there is no settings.xml file in D:// documents \. M2, so the default central library is used. Of course, the internal jar of the company cannot be found. However, why is this?Why does the default library path of Maven change when jdk8 is unloaded?After looking at the settings.xml file, the default repository path is ${user. Home} /. M2/repository. I thought that after uninstalling jdk8, I would restart idea and prompt to select the configuration file directory (I would not prompt again after starting configuration once before). It should be judged here that the value of the environment variable user. Home has changed
wrote a test case

System.out.println(System.getProperty("user.home"));

The output is exactly the directory D: documents
after searching on the Internet, it turns out that this is a bug in jdk1.7 and previous versions, which has been modified since 1.8. http://bugs.java.com/view_ bug.do?bug_ Id = 4787931
jdk1.7 and earlier versions set the user.home environment variable through the registry key
[HKEY_ CURRENT_ User/software/Microsoft/Windows/CurrentVersion/Explorer/shell folders/desktop]
get the value, and then get the superior directory of this path. Use regedit to view the value of the registry key on the PC, which is D:: – documents  desktop. This is a computer provided by the company. Switch the user’s desktop directory to D:  documents  so that personal data will not be lost after the system is reinstalled< after locating the problem, there are many solutions:
1. The path of override settings.xml and repository in idea
2. Execute MVN command-line to add – S C:: (users) ﹣ Jack ﹣ M2 ﹣ settings. XML
3. Copy C: ﹣ users ﹣ Jack ﹣ m2 to D: ﹣ documents ﹣ directory
3

The solution of “unsupported major. Minor version 52” in Java project compilation

Open source software supply chain lighting plan, waiting for you>>>

As shown in the title, the reason for this problem is: this error will appear when the project compiled by the higher version of JDK is put into the eclipse environment where the lower version of JDK is compiled. Therefore, if you want this project to run normally in the low version environment, you can solve it according to the following ideas:

(1) Check the JDK environment variables to ensure that the JDK environment variables have been configured correctly

(2) Modify Java build path:

Right click the project in eclipse, properties – > Java Build Path –> Libraries, delete those that don’t exist, and reselect the existing libraries, such as jdk1.7, tomcat7.0, etc

After this step, refresh the project and recompile it. If you still report an error, please continue to read on

(3) Modify project faces:

As above, right-click the project in eclipse and click Properties – > Project Facets

Here, I mainly modify these two configurations in my circle. The above 3.0 corresponds to jdk1.7, and 3.1 corresponds to JDK1.8

If you can’t modify it here, or refresh the project after modification and still report an error, please continue to read on

(4) Modify org.eclipse.wst.common.project.facet.core.xml:

Open the folder where the project is located, open the. Settings folder, and modify the “org. Eclipse. WST. Common. Project. Facet. Core. XML” file in it

Just as above, modify the version here directly, then go back to the project in eclipse, refresh the project and recompile it

(5) Last trick:

If all the above steps are finished and this error still occurs, we can only make a unique move. That is:

back up the source project

and create a new dynamic Java project in eclipse

copy all the java files, configuration files, foreground pages and other files in the source project to the new project

compile and run new projects

I believe that this step has been achieved and this problem can be solved

PS: the domain name in the picture above is my personal blog’s domain name, which is not reproduced by other websites. Please don’t mark it as “reproduced article” for me

[Solved] Java Call Error: java.lang.IllegalArgumentException: wrong number of arguments

Problem description

Class target. Java has an execute method, which takes a string array as a parameter

public class Target {
    public void execute(String[] args) {
        System.out.println("call execute method with parameter type String[]");
    }
}

Call this method through reflection in the following way

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        String[] parameters = {"1"}; // parameter array
        Class targetClass = Class.forName("Target");// get target class "Target"
        Object instance= targetClass.newInstance();
        Method execute = targetClass.getDeclaredMethod("execute", String[].class);// get target method "execute"
        execute.invoke(instance, parameters);// invoke method
    }
}

As a result, the console reports an error

Exception in thread “main” java.lang.IllegalArgumentException: wrong number of arguments at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at Test.main(Test.java:16)

Problem Analysis

Find the Method.invoke method, which actually receives a variable-length parameter (Varargs).

public Object invoke(Object obj, Object... args)

When the compiler finds something like

method.invoke(object, arg1, arg2)

In such a representation, an array is implicitly created, similar to new object [] {arg1, arg2}, and then is used as the parameter of the invoke method. But if the parameter of the target method is an array, such as

method.invoke(object, Object[])

The compiler will think that you have put all the parameters in the array, so it won’t wrap them again. In this case, the elements in the array , not the array itself, are passed to the target method as parameters

So let’s look back and forth at the above example. In fact, the main method finally attempts to call the execute method with a string type as a parameter through reflection. Let’s do an experiment

public class Target {
    public void execute(String[] args) {
        System.out.println("call execute method with parameter type String[]");
    }

    public void execute(String arg) {
        System.out.println("call execute method with parameter type String");
    }
}

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        String[] parameters = {"1"}; // parameter array
        Class targetClass = Class.forName("Target");// get target class "Target"
        Object instance= targetClass.newInstance();
        Method execute = targetClass.getDeclaredMethod("execute", String.class);// get target method "execute"
        execute.invoke(instance, parameters);// invoke method
    }
}

The final print is (note that the two method parameters are different)

call execute method with parameter type String

Problem solving

In fact, the solution to this situation is very simple, as long as package the array as the first element of the object array , then the compiler will pass the array itself as a parameter to the target method, as follows:

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        String[] parameters = {"1"}; // parameter array
        Class targetClass = Class.forName("Target");// get target class "Target"
        Object instance = targetClass.newInstance();
        Method execute = targetClass.getDeclaredMethod("execute", String[].class);// get target method "execute"
        execute.invoke(instance, new Object[] {parameters});// invoke method
    }
}

Summary

When using reflection to call a method, if the input parameter of the target method is an array, the array should be wrapped in another object array

[Solved] JAVA:java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcodbcDrive

The reason for this problem is that the class can not be found. The following code is normal. It can run in JDK1.6. Oracle has canceled the ODBC bridge after JDK1.6. The solution is to change another driver mode. The current SQL Server driver is com.microsoft.sqlserver.jdbc.sqlserverdriver, and the connection string is jdbc:sqlserver :// localhost:1433; Databasename = database name

/**
 * Author:C
 * Date: 03/15/2020
 * Demonstrate the use of jdbc-odbc bridge to operate the database
 * 1. Configure the data source
 * 2. Connect to the data source in the program
 */
package com.beekc.www;
import java.sql.*;

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

        //2
        Connection ct = null;
        //3
        Statement sm = null;
        try {
            //1. Load the driver
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            //2. Get the connection [specify which data source to connect to, username, password]
            //If you choose Windons NT authentication when configuring the data source, you don't need to fill in the username and password
            //Connection ct = DriverManager.getConnection("jdbc:odbc:beekc");
            ct = DriverManager.getConnection("jdbc:odbc:beekc", "sa", "admin...") ;

            //3. Create a Statement or PreparedStatement
            //Statement use: mainly used to send sql statements to the database
            sm = ct.createStatement();

            //4. Execute (crud, create database, backup database, delete data...)
            //1. Add a data to
            //executeUpdate can perform cud operation, put back int type
            //int i = sm.executeUpdate("insert into stu values('000013','Wu with','Three Kingdoms')");
            //if (i == 1)
            //{
                //System.out.println("Added successfully");
            ///}else{
                //System.out.println("Failed to add");
            //}
            //2. Query
            //ResultSet result set, you can understand the ResultSet as a result set of table rows
            ResultSet rs = sm.executeQuery("select * from stu");

            //rs points to the previous row of the first row of the result set
            //loop out
            while (rs.next())
            {
                String str1 = rs.getString(1);
                String str2 = rs.getString(2);
                String str3 = rs.getString(3);
                System.out.println("sno:" + str1 + "sname:" + str2 + "address:" + str2 );
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //Close resources
            //Close order, create first, close first
            try{
                if(sm != null)
                {
                    sm.close();
                }
                if (ct != null)
                {
                    ct.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
}

Java call ssl exception (javax.net.ssl.SSLHandshakeException: No appropriate protocol)

Today, I used jdk1.8 for the upgrade and found that when Java called SSL, an exception was suddenly thrown.

After a while, I finally found out that there was a problem with the SSL calling authority because of the jdk1.8 version.

Solution: Find the jdk 1.8 installation directory and find a java.security under lib\security in C:\Program Files\Java\jre. Find the corresponding SSLv3, delete it, and restart the project. (Deleting SSLv3 means allowing SSL calls)