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

hi am having this error
I want to find the largest prime of a given number.
This is my solution.
I don't like my solution because I change the variable i in the for loop.
Is there an better solution?

public class LargestPrime {

    public static int getLargestPrime(int number){
            return -1;
        int lpn=number;
        for(int i=2;i<=number;i++){
        return lpn;

    public static void main(String[] args) {

Open in new window

There is a need to add a small method to an existing class inside a JAR file. When I rename the JAR file to zip, I am able to see the Java Class into which I need to add the new method. I do not have a project for this jar as the developer who programmed it is not with the company anymore, and for various reasons the project he developed is not available in the repository. Considering we very rarely need any modification on that jar file, was wondering if it is possible for me to do the required modifications directly within the JAVA file in the JAR, recompile just the CLASS file, re-zip it and rename it to JAR. Since this is an immediate requirement, I felt constructing the project might take more time.

Any inputs/suggestions greatly appreciated :)
Is Taylor Swift a ruthless legal vulture with Indiana Jones - Temple of Doom fiery-ruby eyes?

just kidding :)

In my phone game, I'd like to have pics/icons of everyday objects (sketches) in scenes for a points collection aspect. (and for level advancements)

If I do my own black and white sketches from images I find of Taylor Swift, or Metallica or Jimi Hendrix, or even an elephant, television, car, or an outline of Bolivia, cobweb..

What legal nightmares might I be heading into? Are original outlines of copyrighted images, or close interpretations (my own outlines) of them a path to the guillotine?
Is there a good way in photoshop to generate an amazingly creative approximation of a picture?

For an elephant, I might want icons something like this :

elephant icon
or of Jimi

Jimi Hendrix icon
or Taylor

Dear Gurus,
I am new to Java and trying to write a code where need to match a number 'y' from an array list x[].
If teh number matches, it should give the index value else return the value '-1'
I have written the code and it works...except that when the value doesn't match, it returns '-1' multiple times.
Is there a way that it returns '-1' only once.? Thankyou !

public class findLast {
    public static void main(String[] args) {
        try {
            boolean matchFound = false;
            int[] x = {7, 8, 9, 10, 11, 12};
            int y = 4;

            for (int i = x.length - 1; i >= 0 && matchFound == false; i--) {
                if (x[i] == y) {
                    System.out.println("Index is " + i);
                    matchFound = true;
                else if (matchFound == false){

        catch (NullPointerException e) {
            System.out.print("NullPointerException Caught");

Open in new window

C:\MS\src>java findLast
HI Team,

i am executing below code its working fine when i change the date then check particular row check box  then submit. but it's not working when i clicked on check box first then change the date and submit . please tell me the solution of my problem thanx a ton in advance i m new in java script and jquery so please tell me particular solution on my code .

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<link rel="stylesheet"
<script src=""></script>
<script src=""></script>
$(document).ready(function() {

	$('.chkValues').on('click', function() {
		//get values of dates
		var array = [];
		var parent = $(this).closest('tr');
	    // Now find all the child <inpu> elements with class "date"
	    var last = 0;
	    $('.date', parent).each(function(i,e) {
	      var dt = new Date(e.value.split("/").reverse().join("-"));
	      if (dt.getTime() <= last) {
	        alert('Error: ' + + ' has an invalid value');
	      last = dt.getTime();
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + 

Open in new window

I am seeking advice and suggestions concerning creating PDF documents. I researched many sites but thought I would ask you folks about it.
I will be extracting data from MS SQL Server - 2014 database from many tables to create/populate the PDF document which will be on our web server.
Basically, the user will click a button and code will generate the PDF file.
I can find my way around Java but client doesn't not want to use C or Net.
I use localhost - Win 10 - and mainly PHP - v5.6.25 (client version - no plans to upgrade - their web server is Linux) with Wampserver and Apache 2.4.23.
I have looked at Apache PDFBox - got confused about it. I also took a long peek at iText. I did request a quote but they have never responded to me.
The creation of the PDF document must be created programmatically.
Any thoughts - suggestions - advice would be appreciated.
thank you.
I have a question related with log4j.
I had put file under src folder,  I am using PropertyConfigurator.configure("") to lad the file before calling the logger.
But it can't pick up the file "".
How can i load the file?
there is a spring-servlet.xml under WEB-INF folder, which defined the datasource. Can I add  the property file there?
or can I add a context for this?

Here is an example bean that defined in spring-servlet.xml:
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
          <property name="configLocation" value="/WEB-INF/ehcache.xml"/>
          <property name="shared" value="true"/>

should I do something samiliar like this?      

Any inputs are welcome.
hi am having error running my nodejs

PS C:\Angular3\mean-course> node server.js
app.set("port", port);

TypeError: app.set is not a function
    at Object.<anonymous> (C:\Angular3\mean-course\server.js:47:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
PS C:\Angular3\mean-course> npm install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\watchpack\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2
Do Bullrun and Edgehill, along with some of the inbuilt shortcomings of SSL/TLS itself, mean that encryption amounts to not much more than a myth ?
hold.tarI have failing call to update a table of salesforce. It returns this message:

update Opportunity set NextStep='Contact John Smith' where ID = '0066g00000fjfOqAAI'[ { "message" : "unexpected token: update", "errorCode" : "MALFORMED_QUERY" } ]

Here is my source code

public class SFEngine {
        public static final String clientId="3MVG9LBJLApeX_PDRFsRBGTuqsN.m3Vd1bIwEF5_FNoEUKGVX0gBqUM1YdL52614KXSW9O6pL6abWun9soVyw";

        public static final String clientSecret="8F418A0BCE45412081ED5D3057A20B178C203A05EC368BFC67D82FF5C4BFBD92";
        public static final String redirectUrl="";
        public static  String tokenUrl="";
        public static final String environment="";
        public static final String username="xxxxxxxxxxx";
        public static final String password="xxxxxxxxxxx";                

        public static  String accessToken="";
        public static  String instanceUrl="";
        public HttpClient httpclient;
        public  HttpResponse queryResponse ;
        public  JsonNode queryResults;
        public  HttpGet get;
        public  URIBuilder builder;

private static final String TOKEN_URL =  "";
public static String  OpenRest(String ID, String Field, String Value) {

        String consumerKey = clientId;
Hey i want to use datatables for the first time but it is not working:
THis code is in my header:
        <link rel="stylesheet" type="text/css" href="//">

        <script type="text/javascript" src="//"></script>

Open in new window

And this is the table:
    <table id = "myTable">
            <th>Quiz name</th>
            {% for res in result_sql %}
            {% endfor %}


$(document).ready( function () {
} );

Open in new window

Can anyone find the problem?
is it better to represent as String and Object or will there be any issue in the future ?
Thanks Experts sir.

      public void buildObjectMap() {
            Map<String, Object> objectMap =  getObjectMap();
            objectMap.put("id", id);
            objectMap.put("status", this.getStatus());
            objectMap.put("scheduledDate", this.getScheduledDate());
            objectMap.put("visitationPoint", visitationPoint.toJsonizedMap());
            objectMap.put("teamId", this.getTeam().getId());
            objectMap.put("teamName", this.getTeam().getTeamname());
            objectMap.put("locationId", this.getVisitationPoint().getLocation().getId());
            objectMap.put("locationName", this.getVisitationPoint().getLocation().getName());
            objectMap.put("locationType", this.getVisitationPoint().getLocation().getLocationType().getName());
why data format is being set like this below on createdDate ? IS this correct expert ?
      public void buildObjectMap() {
            Map<String, Object> objectMap =  getObjectMap();
            objectMap.put("user_id", worker.getUsername());
            objectMap.put("session_id", session_id);
            objectMap.put("imei1", imei1);
            objectMap.put("imei2", imei2);
            objectMap.put("macId", macId);
            objectMap.put("session_id", session_id);
            // Date format is defined but it is used in the created_Date format which has been specified here
          DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");  
       // String strDate = dateFormat.format(super.getCreated());  
Hi everyone,

I just did a dependency check in my code and I get:

I've searched in my dependencies (POM.xml and the whole project too) but I could not find netty.
For this reason I think that it is some child dependency.
So I did a maven dependency tree but also searching there didn't get any netty hit.

What am I missing?

Thanks for your help.
Hi Experts,

//Path Traversal Issue
String configuration = path +File.separator+"data"+File.separator+temp+File.separator+id+type+"."+frmt;
File newFilePath = new File(configuration);

Open in new window

please suggest how to change the above to resolve path traversal issue.
Hi Experts,

Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cp " +sourceFile+" "+destFile);

Open in new window

is there any specic reason using the above code or it is legacy code.
can i use alternative approach as below or any better approach is there for file copying

Files.copy(source.toPath(), dest.toPath());

Open in new window

private void submitCallablesWithExecutor()
				throws InterruptedException, ExecutionException, TimeoutException {

			ExecutorService executorService = null;

			try {
				executorService = Executors.newCachedThreadPool();

				Future<String> task1Future = executorService.submit(new Callable<String>() {

					public String call() {
						try {
							processExportRequest(xmlPutRequest_, customizedRequest_, response_);
							return "Success";
						} catch (Exception ex) {
							return ex.getMessage();

			} finally {

				try {
					if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
				} catch (InterruptedException e) {

Open in new window

within processExportRequest I am calling upload to S3.  I have tried both S3Client and S3AsyncClient.  In both cases, I am getting following error:

Failed to upload to S3: java.lang.IllegalStateException: Interrupted waiting to refresh the value.

I don't see anywhere in my code that's calling Thread.interrupt(), and everything else seems to work fine, just not S3 upload.  Maybe the multithreaded nature of Java Future is not compatible with AWS SDK?  Thanks.
Java issue with determining whether a folder is a file or a directory. The following is an excerpt of code that demonstrates the problem:
public static boolean needsNewTable(String version, String schemas, String spreadsheets)  {
            xsdVersion = version;
            File xlsFolder = new File(spreadsheets);
And the output is:

Can someone tell me why I get false for both the isDirectory method and the isFile method (the same holds true for the xsdFolder = new File(schemas) ? Additionally, if I specify an exact schema file and an exact spreadsheet I get false for both methods as well.
Hello Experts,
Am trying to modify an excel file having multiple rows using Apache POI 3.17 (i.e. remove the rows). When I tried to remove the rows in the first while loop, I used to receive the error concurrentmodificationexception. I tried moving all the rows into a list and then delete it in a separate loop as suggested in one of the forums. I now receive XmlValueDisconnectedException. Can anyone please suggest what might be going wrong here?

public static void removeFalseRows(String readFilePath, String writeFilePath, String sheetName) throws IOException, InvalidFormatException {
		List<Row> toRemove = new ArrayList<Row>();
		FileInputStream fsIP = new FileInputStream(new File(readFilePath));
		Workbook wb = WorkbookFactory.create(fsIP);
		Sheet sheet = wb.getSheet(sheetName);
		Iterator<Row> rowIterator = sheet.iterator();
		while (rowIterator.hasNext()) {
			Row row =;

			if (row.getCell(5).toString().equals("false")) {

		for(Row R : toRemove) {

		for(Row R : toRemove) {
			int rowIndex = R.getRowNum();
			int lastRowNum = sheet.getLastRowNum();
			if (rowIndex >= 0 && rowIndex < lastRowNum)
				sheet.shiftRows(rowIndex + 1, lastRowNum, -1);

Open in new window


I have issue with the code base can some body help me, i am working on JPA but issue is how to pass the value in the findByOrgUnits
which is not correct. The value need to pass is a List value to the other screen. The content is List value which need to be pass to the
 the JPa Below, but the issue is which passing orgUnitTypes i am getting variable is not set correct in the input itself.

public AdminDTO getAllLookupData(int pageNo, int pageSize, String sortType, List<String> sortFields, String locale)
throws CmsDaoException {
            OrgUnitsLang orgUnitsLang;
            Long orgUnitId = orgunit.getOrgunitId();
            Set<OrgTransactionTypes> orgTransactionTypes;
            Languages languages = languagesRepository.findByLocale(locale);
            OrgUnits orgUnit = orgUnitRepo.findByOrgunitId(orgUnitId);
            OrgUnitTypes[] orgUnitsLang;
            List<OrgUnitsLang> orgUnitlang = orgTransactionTypesRepo.findByOrgUnits(orgUnitTypes);
            The code below
    public interface OrgTransactionTypesRepository extends JpaRepository<OrgTransactionTypes, Long>, JpaSpecificationExecutor{

	//to retrieve transaction type ids 
	List<OrgTransactionTypes> findByOrgUnits(OrgUnits orgUnits);
	OrgTransactionTypes findByOrgUnitsAndTransactionTypes(OrgUnits orgUnits,
			LookupTransactionTypes transactionTypes);

	@Query("SELECT orgTransactionTypes from OrgTransactionTypes orgTransactionTypes where orgTransactionTypes.orgUnits in :unitList")
	public List<OrgTransactionTypes> 

Open in new window

I want to upload a file to S3 bucket, but my company want to use IAM role as opposed to access keys.  This is AWS documentation on how to upload to S3 asynchronously:

S3AsyncClient client = S3AsyncClient.create();
		CompletableFuture<PutObjectResponse> future = client.putObject(
		future.whenComplete((resp, err) -> {
			try {
				if (resp != null) {
					System.out.println("my response: " + resp);
				} else {
					// Handle error
			} finally {
				// Lets the application shut down. Only close the client when
				// you are completely done with it.


Open in new window

I don't see anywhere to put in IAM role info.  I tried to put it in ~/.aws/credentials in this form:


role_arn=<the ARN of the role you want to assume>

but so far haven't gotten it to work.  I read somewhere you need to use STSAssumeRoleSessionCredentialsProvider but didn't see any good examples.  My main question is do I even need to do anything if I already assigned the IAM role to an ECS instance.  Can someone help me?   Thanks.
I have a utility class TransactionType

public  setOrgTransMap(List<OrgTransactionTypes> list,long count, List<LookupConfigValues>  lookupConfigValues, List<Languages> languageList,String locale) {

Open in new window

I am calling setOrgTransMap in another in the dao class called Xnr( Just to keep secret)

public orgTransactionTypesUtility.setOrgTransMap(newOrgTrasnTypesList, COUNT,configValues, languageList,locale);

Open in new window

But i am giving all the input values but i am getting "configValues cannot be resolved to a variable"
By the way configValues  is not coming in the current DAO class, is it issue with my code or I am lost the java class.
Netbeans project's dialog box
This is probably very simple. The above dialog box is arrived at by right-clicking on a JavaFX project, then selecting Properties, then clicking Run, and you should have something like the image.

Notice the pathname I highlighted within a red rectangle. That is the full path to my JavaFX SDK. I already have that entire path stored in an environment variable called PATH_TO_FX.

I tried to substitute the pathname with %PATH_TO_FX% (without quotation marks), but it didn't work.

So am I doing something wrong? Or does Netbeans simply disallow such notation? Can someone confirm?

What am I doing wrong? Or does Netbeans really do not accept environment variables in this part of its dialog box?
I need some advice/guidance/suggestions. I am using localhost,  Win 10 . both IIS and WampServer  (Apache 2.4.23) are running (each have their own listening ports), and have both PHP 5.6.25 and 7.0.10 installed. I sometimes do work with classical ASP. With all being said, I have the need to extract data from pdf files and insert the data into a db.
I thought it would be easier for me to convert them to XML documents. This needs to be achieved programmatically and not at the CLI level.
I have pretty much decided that Java would be good to use (although I am far more comfortable with PHP) and have already posted two questions concerning the project.
WHAT I think I need is to have a IDE for my Java. I normally use Notepad++ (and sometimes CodeIgniter) Would Netbeans IDE be good to use ??
I am not very versed with Java, I am better with PHP.
If anyone has any suggestions and/or pointers for me about any of this - I am all ears and listening.
Thank you.






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.