Java

99K

Solutions

33K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

Share tech news, updates, or what's on your mind.

Sign up to Post

Avoid Empty Catch Blocks
It’s a very bad habit to leave catch blocks empty, as when the exception is caught by the empty catch block, the program fails in silence, which makes debugging harder. Consider the following program which calculates sum of two numbers from command-line arguments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Sum {
    public static void main(String[] args) {
        int a = 0;
        int b = 0;
 
        try {
            a = Integer.parseInt(args[0]);
            b = Integer.parseInt(args[1]);
 
        } catch (NumberFormatException ex) {
        }
 
        int sum = a + b;
 
        System.out.println("Sum = " + sum);
    }
}
Note that the catch block is empty. If we run this program by the following command line:
1
java Sum 123 456y
It will fail silently:
1
Sum = 123

Open in new window


when i tried above example i am getting different error as below istead of getting 123


public class Sum {
    public static void main(String[] args) {
        int a = 0;
        int b = 0;
 
        try {
            a = Integer.parseInt(args[0]);
            b = Integer.parseInt(args[1]);
 
        } catch (NumberFormatException ex) {
        }
 
        int sum = a + b;
 
        System.out.println("Sum = " + sum);
    }
}

Open in new window


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
      at Sum.main(Sum.java:7)

https://www.codejava.net/coding/10-java-core-best-practices-every-java-programmer-should-know

even below good catch block example also gives same error
public class SumFixed {
    public static void main(String[] args) {
        int a = 0;
        int b = 0;
 
        try {
            a = Integer.parseInt(args[0]);
            b = Integer.parseInt(args[1]);
 
        } catch (NumberFormatException ex) {
            System.out.println("One of the arguments are not number." +
                               "Program exits.");
            return;
        }
 
        int sum = a + b;
 
        System.out.println("Sum = " + sum);
    }
}

Open in new window

Please advise
0
Become a CompTIA Certified Healthcare IT Tech
LVL 12
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

I have installed NetBeans IDE 8.2. When I try to create a new project. Start File --> New Project. Nothing come out without any error.  JDK has been installed. Any idea ?

Thx


https://netbeans.org/downloads/
0
thanks for the compliment s from experts exchange that is the my second question what is the write way to play and browse a file that can be downloaded from java in the following format like jpj,PNG,text,docx,xisx,PDF and more.my question is that what is a java and what is the process to run java and java script in any mobile number and can I have to run in any mobile device through any of the email I'd.  solution this question in any way that is possible. and one thing is that ican play movies and videos  through java script was this any of the way you would have to like to suggest me immediately. thank you again experts team.
0
Whi can iam confirm a java script in any other mobile device and any other emaaddress and run it confidentialy please suggest me that what is the process to run the files that can,t be support the device.thease are the files mean java files or non supported files system can,t be display like zip files,axp,jpg,txt,docx,xisx,pdf,or more forms files.or a video format files that can be have to downloaded queue but system does not support to play and run thank you again
0
Hi, my web site has a request information form page which uses formmail.pl. Lately I've been receiving a lot of robot generated emails from the page so I decided to put a option box on the page whereby if the option "Human" is not selected, then no email will be sent through the formmail.pl file.

I've not too experienced with this and I've not worked with JavaScript for a long time, thus I can't get my idea to work.

On the page is a form which I've described as below:
<form name="infoRequest" enctype="application/x-www-form-urlencoded">
<input name="subject" type="hidden" value="Information Request">
<table width="100%" border="0" cellspacing="0" cellpadding="0">

I then put in a select option box for a visitor to select a value from the list:
<tr>
<td height="30" width="33%">what am I:</td>
<td textarea rows="3" cols="30" height="30" width="67%"</TD>
<select name="robotyn" onchange="checkrobot();" id="dropDown1">
        <option value="Robot">I'm a Robot</option>
        <option value="Human">I'm a human</option>
        <option value="other">Other</option>
</select>
</tr>

below that is the submit and reset buttons. My intension is for a script to be run when the submit button is checked.

<tr>
<td colspan="2" width="100%" align="center">
<input TYPE="submit" NAME="Submit" VALUE="Submit" onclick="(function() {checkrobot();return false;})()"><input TYPE="reset" VALUE="Reset">
</td>
</tr>

here is the script:
function checkrobot(){

  a = …
0
Dear Experts

I am using Glowroot to monitor performance of my jvm application. Wanted to understand that how much processing is done in jvm side and how much in db side.
So, I see the attached report of the glowroot.

With this attached file my understanding is like this:
Total time taken is 13,899 seconds.
Out of that Timer 1 is running for 13,879 seconds, and out of those time time, 6,106 seconds is by jdbc. So around 7000 seconds is only in timer?

So am I reading the report correctly? That my jvm is spending more time than the jdbc. So to improve performance I need to look into why timer is taking so much time?

If you have idea about this glowroot kindly share.

Thanks in advance.
Glowroot.bmp
0
Hi Experts,
how to form a dynamic string array from the below inputs

String countries="sg,sk,hk,ke" //this string having country names dynamically
countries max will be five and min will be one value separated with comma(,)


i have to form dynamic string array based on above countries
user can choose any country but max will be 5 countries min 1 country
country values are dynacmic

how to form dynamic string array

exmaple:
new String[] {"sheet one"+ "sg" , "sheet two" + "sk","sheet three" + "hk","sheet four" + "ke","sheet five" + "ug","summary"}
new String[] {"sheet one"+ "sg" , "sheet two" + "sk","sheet three" + "hk","sheet four" + "ke","summary"}
new String[] {"sheet one"+ "sg" , "sheet two" + "sk","sheet three" + "hk","summary"}
0
Hello Experts,

I was writing a restful apis
I would like to have a snippet of code to  which will handle the exception like
If request was successful, then return 2xx code (3xx for redirect).
 If there was an internal logic error on a server, then return 5xx. If there is anything wrong in client request, then return 4xx code.
 like to have a user friendly description of the errors...

Thanks
0
I have a simple java project with 4 java classes. I am trying to compile it using make for research purpose. All java files are placed under Test/MyProj directory and makefile is also there. Below is my makefile -

JFLAGS = -g -cp .
JC = javac
.SUFFIXES: .java .class
.java.class:
	$(JC) $(JFLAGS) $*.java

CLASSES = \
	Way.java \
	Sport.java \
	SportTester.java \
	Area.java 

default: classes

classes: $(CLASSES:.java=.class)

%.class : %.java
	$(JC) $(JFLAGS) $<

clean:
	$(RM) *.class

Open in new window


This is the error I am getting after running make. I have set javac correctly in PATH variable. If I run javac *.java from the same command prompt it works fine. What could be the problem?

C:\Test\MyProj>make
javac -g -cp . Way.java
javac -g -cp . Sport.java
Sport.java:10: error: cannot find symbol
        private Place currPlace;
                ^
  symbol:   class Area
  location: class Sport
Sport.java:11: error: cannot find symbol
        private Vector<Area> vecAreas;
                       ^
  symbol:   class Area
  location: class Sport
Sport.java:52: error: cannot find symbol
        void setCurrArea(Area p) {
                          ^
  symbol:   class Area
  location: class Sport
Sport.java:15: error: cannot find symbol
                vecAreas = new Vector<Area>();
                                       ^
  symbol:   class Area
  location: class Sport
Sport.java:16: error: cannot find symbol
        

Open in new window

0
Install WindowBuilder Plugin in Eclipse but it get the followings errors :

Eclipse is running 0, but this Java project has a 10 Java compliance level, so WindowBuilder will not able to load accesses from this project.

Any idea ? Does WindowBuilder support latest Java version ? Is it still support in future Java or I should use other gui tools ?

Thx
0
Starting with Angular 5
LVL 12
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

how to read the csv file which is in AWS s3 bucket

aws s3 cp command will copy the file but i need to validate before copy the file ? is that possible ?
0
I have a java project(using struts) running under weblogic app server in production without any problem. however, after i migrate it to the Tomcat app server, it always report the following error message for a specific action.

Error creating form bean of class org.apache.commons.beanutils.LazyDynaBean
java.lang.NoClassDefFoundError: org/apache/commons/validator/ValidatorException
      at org.apache.struts.config.FormBeanConfig.createActionForm(FormBeanConfig.java:219)
      at org.apache.struts.util.RequestUtils.createActionForm(RequestUtils.java:292)
      at org.apache.struts.util.RequestUtils.createActionForm(RequestUtils.java:191)

the tomcat server enviroment is below:

[root@server85 logs]# cat catalina.out 
01-Sep-2018 19:25:25.637 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/9.0.5
01-Sep-2018 19:25:25.639 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Feb 6 2018 21:42:23 UTC
01-Sep-2018 19:25:25.639 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         9.0.5.0
01-Sep-2018 19:25:25.639 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Linux
01-Sep-2018 19:25:25.639 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            4.1.12-94.3.9.el7uek.x86_64
01-Sep-2018 19:25:25.639 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          

Open in new window

0
What are all the package need to access docker to lambda


lambda will call s3 bucket .

I need automated script (that script will daily mid night will run)
0
how we can read s3 bucket files form docker container
what are the package needed and what is the command

how we can put data to maria DB form docker container
what are the package needed and what is the command
0
I am working with matcher and pattern in Java. I think this test code should work to add and print my desired search but it is not. If anyone can take a look and fix this it would be much appreciated. Note the if I just use the while loop it works fine. It is when I add in the for loop to iterate through the array list is when it prints out blank.

Screen-Shot-2018-08-29-at-11.51.28-A.png
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test {


    public static void main(String[] args) {

        ArrayList<String> linet = new ArrayList<>();
        ArrayList<String> lines = new ArrayList<>();

        lines.add("O#833452-14943408 PO#Subject: Re: gg  - Oops. Your O#purchase order is missing key payment information.PPO O#769117789:C11134 [ ref:_00D30dWxY._5001311TVgB:ref ]");
        lines.add("SO#833452-14943408 PO#Subject: Re: gg  - Oops. Your O#purchase order is missing key payment information.PPO O#769165189:C11134 [ ref:_00D30dWxY._5001311TVgB:ref ]");
        lines.add("O#833452-14943408 PO#Subject: Re: gg  - Oops. Your O#purchase order is missing key payment information.PPO SO#7696561189:C11134 [ ref:_00D30dWxY._5001311TVgB:ref ]");
        lines.add("CASE-1443453931800\tPN#109684324201-2 qty1EA\t\"");

        for (int i = 0; i < lines.size(); i++) {

            String line = lines.get(i);

            String so1 = "SO#";
            Pattern p = Pattern.compile(so1);
            Matcher m = …
0
How to find how many records present  in csv file using Java
The file will be present in S3 location . Is there any AWS services available for this ?
0
Hi

We are using dbcp2.x as connection pool library. Have set the property of maxActive as 100. When we run 20 threads in parallel, 2 threads keep waiting for connection and never gets it!!

Is this kind of issues already known as bug in dbcp2?
Kindly share if you have come across with similar issue.

Thanks.
0
how to mock class variables using mockito java

In my class i declare String variable , i want to mock the value how to do that

class A{

  @Value("${COUNT_SQL}")
private String test="sql query";

}
i want to mock this test
I used MemberMatcher.field but its not working giving Null pointer exception
0
HTTP Status 404 ? Not Found
Type Status Report

Message /myapp/WEB-INF/views/verification.jsp

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
0
Learn Ruby Fundamentals
LVL 12
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

I need to open 5 browser windows and position them on the screen so they don't overlap.  I'm envisioning them not having the full frame - don't want the tabs atlong the top, don't want the address bar, etc.  Just a thin frame around the windows (which will be video cameras from Nest).  Each has a unique URL

Anyone know of a script / powershell / something else that will allow that?  Click on it and it opens the windows, sized, placed correctly and in bare bones frames?

I can drop in the correct URL to a script.  The URLs would look like:  https://home.nest.com/camera/3cb550e7abbf4cf6ad794c97824c72e2

The machine would also be used for general surfing, so setting home pages isn't really the best answer (if that's even an answer)
0
Is there any way to know that HashMap resizing is occurring and how many times?
0
How to right code coverage for preparedStatment lambda action

this.jdbcTemplate.query(sqlQuery, (PreparedStatementSetter) ps -> {
            ps.setTimestamp(1, startTime);
            ps.setTimestamp(2, endTime);
            ps.setString(3, status);
            ps.setString(4, Constants.SUCCESS);
            }, new CountResultSet()).intValue();
0
PowerMockito.when(this.jdbcTemplate.queryForObject(Matchers.anyString(), Matchers.<Object[]> any(),
                        Matchers.<Class<Long>> any())).thenReturn(0L);

 PowerMockito.when(this.jdbcTemplate.queryForObject(Matchers.anyString(), Matchers.<Object[]> any(),
                        Matchers.<Class<Integer>> any())).thenReturn(1);

I have right PowerMockito test case for my class . both queryForObject in same method
while execute  2 second queryForObject in my main class  its giving error  
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
0
Hello Experts,
I need to add a Java Eclipse Project into BitBucket which will be cloned and used by the team. While I do have the experience of creating a GIT repository to maintain some XML files, I was wondering what care needs to be taken while adding an entire project (like the files that needs to be ignored, etc). Also, I would be interested to know if there is a way to internally link a JAR file of this Java project into the folder of another project in the same repository.
0
is it possible to assign some value to pass by references method in mockito unit test

eg:

test(input,input1);
i   need to change the value of input after return  ? is that possible??
0

Java

99K

Solutions

33K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.