Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x

Java

99K

Solutions

32K

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

Did you know that Android App developers have a high earning potential? Add this skill to your resume to increase your future earnings. Enroll in January’s Course of the Month today!
0
Get your problem seen by more experts
LVL 11
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.
0
January’s Course of the Month is now available! Enroll to learn how to build Android apps and pad your resume for future career opportunities.
0
Immutable Class Builders
 
The other day I showed 1 way to make a Class #Builder more meaningful, #semantically, leveraging the #programming language's type system. Today, I'm going to address how to make them immutable, its benefits, and its drawbacks.
 
Why?
 
Class Builders typically use mutable architectures where the programming language allows. In #Java we often see the following model:
 
@Immutable  
final Class Person {  
 
public final Name name;  
public final Address address;  
 
Person(final Builder builder) {  
  this.name = builder.name:  
  this.address = builder.getAddress();  
}  
 
}  
   
@Mutable
final class Builder {  
 
public final Name name;
@Nullable private Address address;
 
private Builder(final Name name) {
  this.name = name:  
  this.address = Address.empty();  
}  
 
public static Builder named (final Name name) {  
  return new Builder(name);  
}  
 
public Builder with (@Nullable final Address address) {
  this.address = (null == address) ? Address.empty() : address;
}  
 
public Address getAddress () {
  return (null == this.address) ? Address.empty() : this.address;
}  
 
public Person build () {  
  return new Person(this);
}  
 
}  
 
Whatever Person field is required, we find in the Builder's constructor. In the above example, that's Name.
 
Other fields are optional, and their value is added to a Person instance by using one if the Builder.with() instance methods.
 
Note how the Builder also features a …
0
 

Author Comment

by:A.E. Veltstra
Thank you, Brian! I'll look into that.
0
 

Author Comment

by:A.E. Veltstra
Anton Shipilev showed in 2014 that using all final fields and setting them in the class constructor did in fact slow down initialization when using Oracle's HotSpot Java compiler on ARM and PowerPC. I have yet to see whether his recommendations have been committed. https://shipilev.net/blog/2014/all-fields-are-final/
0
Type-safe class builders
 
The Builder design pattern for software architecture has found quite some traction among people who read the design patterns book by the Gang of 4, as well as those who seek a more fluent, clean-code approach. Oddly enough, these 2 approaches conflict. In this article I'll focus on the latter approach.
 
Uses for the Fluent Builder pattern include reduction of nullable constructor parameters of the target class, reduction of the number of constructors of the target class, reduction of the amount of parameters for constructors of the target class, and providing semantically meaningful method names to specify parameter values for the constructors of the target class.
 
And I find that in the latter use, implementations tend to be lacking.
 
For instance, a typical example is shown in Lokesh Gupta's Builder article over on HowToDoInJava. Read it.
 
Using that Builder reads like this (I have altered it slightly):
 
final User lokesh = new User.UserBuilder("Lokesh", "Gupta").mice(1).desk(14).monitors(3).build();
 
All the hallmarks of a fluent API are there, aren't they?
 
Well. Not really.
 
See, its method mice(int) doesn't signal what its effect will be. "Mice" is just a noun. Not a verb. This is common in Java POJO design, but it shouldn't be here. For self-describing code, I also expect that a setter method signals its effect. Something like setMice(int).
 
But what does that number signify? A type? An amount? Something else? Let's …
1
It seems like an entropy daemon like "haveged" (http://www.issihosts.com/haveged/) can significantly reduce Tomcat start up times.  Java uses /dev/random by default to initialize seed generators.  Problem is, if the entropy pool on a machine is depleted, /dev/random will block until enough environment noise has been gathered to generate sufficient entropy. haveged helps keeps the entropy pool filled up.
2
 
LVL 10

Expert Comment

by:Brandon Lyon
This is another example of why backends can be hard to get right and are more difficult than they seem. There are so many important minor details.
0
Hello
I'm a new to programming and I need help with a problem please.
I'm trying to call a method (addEmployee( with an Array parameter) from the Department class to the Testing Class through the object sales. However, I cannot seem to to this.
The following line:     sales.addEmployee(alex); // This line is underlined red 'Cannot resolve symbol addEmployee'

// TESTING CLASS
public class TestCompany {

    Employee alex = new Employee("Alex Rod", 6);
    Employee linda = new Employee("Linda Berry", 7);
    Employee john = new Employee("John Doe", 3);
    Employee sara = new Employee("Sara Time", 7);
    Employee james = new Employee("James Doe", 4);

    Department sales = new Department("XYZ Sales");
    Department IT = new Department("XYZ IT");

    sales.addEmployee(alex); // This line is underlined red
    sales.addEmployee(linda);
    sales.addEmployee(john);

    IT.addEmployee(sara);
    IT.addEmployee(james);
}

//DEPARTMENT CLASS
public class Department {

    private String deptName;
    private double budget;

    private Employee[] emps = new Employee[5]; //creates 5 boxes of employees (from Employee Class)
    private int counter =0;

   public Department(String deptName){
       this.deptName = deptName;
       this.budget = 50000;
    }

    public void addEmployee(Employee obj){
       emps[counter] = obj;
       counter++;
    }
}


//EMPLOYEE CLASS
public class Employee {
   
    private String empName;
0
 

Author Comment

by:Kevin Blakely
Duh!!! I forgot to add public static void main !!! Sorry SOLVED
0
 
LVL 2

Expert Comment

by:Paul Kent
For future reference, you will receive better assistance if you publish your problem as a Question rather than as a Post. (Click the blue "Ask a Question" button above to ask a question.)
1
#TodayILearned: #Gradle for #EclipseIDE is quite stubborn when it comes to adding a JVM container to one's #Java projects.
 
Every time I update the JVM (in this case to 1.8.0_152) I need to tell Eclipse and Gradle which JVM to run, and which JVM to apply to my Java projects. When we tell Gradle to apply the java plug-in to a project, it automatically inserts some random JRE that isn't defined anywhere. It most certainly isn't the SDK that my projects need.
 
To solve this, we can set the Eclipse classpath from the Gradle build script, after we tell Gradle to apply the eclipse plug-in to a project. It looks like this:
 
def sdkName = 'SDK 1.8.0_152'
def sdkContainerPrefix = 'org.eclipse.jdt.launching.JRE_CONTAINER'
def sdkContainer = sdkContainerPrefix +  '/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/' + sdkName

eclipse.classpath.containers sdkContainer

And then Gradle nicely adds TWO (2) JVM containers: the random JRE it defined in some unknown location, plus the SDK we just specified.
 
(Note: the SDK specified above bears the name 'SDK 1.8.0_152'. This is a custom name chosen by me. It is the same as I chose in Eclipse' preferences for Java -> Installed JREs. In my set-up, it is the only JRE I specified, and therefore the default.)
 
To fix this, with Gradle 4.3.1, we get to undo part of what Gradle's java plug-in does. Instead of the above instruction, we do this:
 
project.afterEvaluate {
  project.eclipse.classpath {
    containers.removeAll …
0
#TodayILearned how to get Gradle to deploy my application distributions and their dependencies to target application servers and library repositories.
 
It has been a missing piece in the automation of my deployments. Gradle already generates the application distributions, but the deployment there-of still was a manual affair.
 
My applications usually are grouped in suites. All applications in a suite share the same base library. That gets assembled and deployed first. Both happen via Gradle. For deployment, I use Gradle's uploadArchives task, from its Java-Library plug-in. This is my script:
 
uploadArchives {
  repositories {
    flatDir {
      dirs localLibFolder
    }
    flatDir {
      dirs sourceRepository
    }
    flatDir {
      dirs targetLibFolder
    }
  }
}
 
My script fills in folder paths for the parameters localLibFolder, targetLibFolder, and sourceRepository.
 
The script also uses that targetLibFolder  in my custom task of type Copy, that generates the individual application distributions. Each app will be distributed in a handful of flavors, and they need to know where to find the libraries on which they depend. Those are stored in the targetLibFolder.
 
Next, another custom task of type Copy depends on my custom task generateDistribution, and copies the distribution to a target folder on the target app server.
 
Each distribution and deployment gets timestamped, so multiple versions can exist next to each other.
 
The last challenge I …
0
We are almost up to Java 9 and there still seems to be no way of copying streams in Java without putting all the boilerplate. So i still seem to need THIS
Please let me know if i'm wrong
0
 
LVL 28

Expert Comment

by:rrz
The first thing I wrote with Java 9.
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/inOut")
public class InOut extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    response.setContentType("text/plain");
		request.getInputStream().transferTo(response.getOutputStream());
	}
}

Open in new window

and called it with
<html>
	<body>
        <form action="inOut" method="post">
		    param1:<input type="text" name="p1"/>
			param2:<input type="text" name="p2"/>
            <input type='submit' value='Submit'/>
        </form>
	</body>
</html>

Open in new window

0
 
LVL 86

Author Comment

by:CEHJ
There are probably other instances of other long overdue boilerplate breakers too, but i can't think of them

Of course with my stream copier, you can decide about the closure of both streams ;)
0
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Just saw some advertisement where there was code catching a null pointer exception. Are people really out there catching null pointer exceptions. Seems like poor coding style when you can check if the variable is null before hand. We have also been using Java annotations to mark something as null able or not null. This has been really helpful in making potential null pointers compile time errors. Just a random thought.
2
#TodayILearned that sometimes, the #Java #CharBuffer can't give an #array of the #CharSequence it #wrap ped.
 
That happened with a #StringBuilder instance, which implements CharSequence.
 
A CharBuffer's array() method normally returns the char[] array that backs it. But the method will throw an #UnsupportedOperationException if no such array is available. And that is exactly the case I encountered today, when I had it wrap a StringBuilder.
 
So instead, we use CharBuffer.get(dest), in which we define dest as a char buffer of the desired size.
 
In my case:
 
final char[] buffer = new char[input.length()];
CharBuffer.wrap(input).get(buffer);
 
Happy coding!
0
A technology that has been really helpful as a Java developer is the ability to hot swap code using a technology like jRebel. Not having to restart the application server every time I make a change has really sped up development.
1
Last chance! Today is the final day to enroll in courseofmonth-native.JPGJuly’s Course of the Month, which prepares you for HTML5 certification. Premium Members, Team Account members, and Qualified Experts unlock this course for free as part of their membership! Once you enroll, you’ll have 30 days to take the course.
4
Boasting Java's speed.
 
Java suffers the myth that it is slow. Those who perpetuate this myth, seldomnly explain exactly what's slow. Benchmarks that do exist, oppose this myth in some cases, and strengthen it in others.
 
So here's some anecdotal evidence to boast Java's speed.
 
I've been developing a JavaFX-based data-editing GUI, to be used by lay people. Its start up from the IDE (Eclipse) is so fast, that its first screen gets displayed in under 3 seconds.
 
Now, I'm assuming that it'll be a bit slower on a client computer, where the JVM isn't running yet. And those computers might be restricted in memory, slowing down the application over all.
 
I'm also developing and maintaining several tens of data-integration applications, for which I frequently run integration tests.
 
Running on their application server, from starting in Windows Task Scheduler, to the moment where they read and archive their input file, tends to take less 5 to 10 seconds.
 
Running in my copy of their IDE (Eclipse), from starting in JUnit, to the moment they read and archive their input file, tends to take 2 to 5  seconds.
 
A factor in the difference between start-up times between IDE-run or Task-Scheduler-run is, well, the Windows Task Scheduler. My IDE might have a bit more memory to run, but the individual applications get restricted in the same way as they are on the app server. Maybe JUnit performs some wizardry that keeps the compilation "hot"?
 
Yes, I have seen some of …
2
 
LVL 7

Expert Comment

by:Brian Matis
Good to hear! Personally, I've never learned any Java (the syntax has always just looked really weird to me—but I'm sure part of that is just that I'm only a hobbyist, with only some basic experience in C, ASP, PHP, and Python) but I've certainly heard some of the grumbling of Java's speed. I've always been a bit intrigued to learn some Java, especially given its popularity, and it's nice to hear a positive viewpoint. Thanks for sharing!
0
3
 
LVL 54

Author Comment

by:Scott Fell, EE MVE
I don't think I shared it for how to catch a bullshitter, but more for the good points to think about in how we work.  A lot of this may be standard operating procedures in their daily lives and others may not.  

My big takeaway is understanding the problem objectively and asking the right questions before forging ahead,.  What problem is this going to solve, what are the costs (not just $$ but time/people),

Some good points for day to day work process.
3
 
LVL 11

Expert Comment

by:Jeffrey Dake
I totally agree, there are some good points in there about questions we should ask ourselves before we continue developing. I have seen plenty of "refactors" that made the code more reusable but there were no plans to reuse the code. By the time another developer got the chance to reuse it, the original assumptions were no longer valid and another refactor was needed.

As developers we should always be trying to balance how we solve problems with the benefits of how we solve them.
3
#TodayILearned that #OData presents a problem for #XSLT. The #JSON element named "@odata.context" can't be translated into an #XML element with the same name, using XSLT 2 or 3 as provided in #Java by #Saxonica.
 
The problem is that XSLT uses that @ in XPATH statements to match element attributes, and in other places within curly brackets, like {@attribute}, to copy that attribute's content into the output.
 
The solution is to differentiate between nodes/attributes that do, and ones that don't contain an @-sign,  and either replace() or translate() that into something else.
 
In my case, I use fx:json-to-xml() from XSLT3, implemented by Saxonica, to transform received JSON-formatted data into raw XML. This leads to a map element that contains elements array, boolean, map, null, number, and string. The JSON element names become the XML elelements' "@key" attribute.
 
A 2nd XSL transformation produces the domain-specific XML-format. As stated above, we must take heed with producing the "@odata.context" element. This can occur, a.f.a.i.k., in either a null element or a string element. So, we differ between those with and without an "@" in the key attribute:
 
Without:
<xsl:template match="xf:string[@key][not(contains(@key, '@'))]">
<xsl:element name="{@key}">
<xsl:value-of select="text()" />
</xsl:element>
</xsl:template>
 
With:
<xsl:template match="xf:string[@key][contains(@key, '@')]">
<xsl:variable name="newName"><xsl:value-of select="translate(@key, '@', '')" …
0
 

Author Comment

by:A.E. Veltstra
Hi, Andrew Leniart. Funny, we have the same first name.
 
Thank you for your concern. I did search before I found a way to solve my problem and published it. As far as the search could tell me, I'm literally the first person to encounter and solve this problem. Hence the publication.
0
 
LVL 12

Expert Comment

by:Andrew Leniart
My apologies Andrew, I didn't read your entire post carefully enough and took it to be a problem you were still trying to solve. I think the hash tag # at the start threw me off! These new fandangled ways you younger generation have of talking can get confusing for oldies like me! lol..

Cheers :)
1
#TodayILearned a #gotcha with #Predicate in #Java. You can learn, too!
 
Here's 1 way to write a Predicate:
 
static Predicate<String> isEmpty() {
    return p -> 0 == p.length();
}

And here's another way:
 
static Predicate<String> isEmpty = (p) -> {
    return 0 == p.length();
}
 
Erm. What's the difference?
 
Well. The first is a method that generates a function, and you call it like this:
 
boolean test = isEmpty().test("Hello!");
 
Or, from a stream in a method in a class named World:

.filter(World::isEmpty())
 
The second is a field with a pregenerated function, and you call it like this:
 
boolean test = isEmpty.test("Hello!");
 
Or, from a stream in a method in a class named World:

.filter(World.isEmpty)
 
Notice how the method-based Predicate still has to generate a function, and thus has to be called with parentheses.
 
The field-based predicate already generated its function by the time it gets called, and because it's a field, no parentheses are used for accessing it.
 
Why Predicates at all, rather than a simple boolean-returning method?
 
Beats the heck out of me. 
2
Apple is no longer just for the tech-savvy millennial and professional crowd. Check out today's product release, where developers as young as 7 and as old as 84 are releasing new apps to the App Store. https://www.apple.com/apple-events/june-2017/
6
 
LVL 15

Expert Comment

by:Joseph Hornsey
Wait... Apple users are "tech-savvy"?  Huh.
3
Free Tool: ZipGrep
LVL 11
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Is Java a terrible first programming language to learn? Do you agree with Stanford switching their intro course to JavaScript? Or would you have picked something else?

https://thenextweb.com/dd/2017/04/24/universities-finally-realize-java-bad-introductory-programming-language/#.tnw_AFXiESVy
2
 
LVL 11

Expert Comment

by:Jeffrey Dake
I definitely think there is something better to start with than Java, but not sure JavaScript is the answer.
1
 
LVL 7

Author Comment

by:Brian Matis
I imagine the appeal of JavaScript is how you can run it in a browser and don't need to worry about dev environment setup or learning a command line to get started.

What language would you choose, Jeff?
0
When I went to school to get my degree in SE I had the importance of Java Docs beaten into me on a daily basis. Now that I am in industry, I find that Java Docs are the last place I look - instead opting for Q&A sites or google searches for blog articles due to the specificity of the problems I come across.

I was never encouraged to do this sort of research in practice, in fact, it was often discouraged. There definitely seems to be a disconnect in school professors and their outdated methods and actual industry practices. Maybe in schools that are research oriented this is better since engineering professors are actively working in their field, but at my public university I had professors who were perplexed by syntactic sugar that is now common place such as the
for ( x : y )

Open in new window

loop.
5
 
LVL 9

Author Comment

by:James Bilous
I had an interesting situation where I earned my BS and MS in computer science from the same university in a blended program ( I earned both degrees at the same time ). My school prided itself in project based learning, in fact the motto of the school was "Learn by Doing". I definitely got a great education because of this philosophy and most of the professors were great, but the ones that taught fundamentals (read 101, 102, 103 programming courses) were absolutely horrific.

By the time I hit graduate level coursework the professors were, again, fantastic. These were all instructors who were very active in industry and research and many had side companies they worked on. I think the critical missing piece from the earlier instructors was their lack of participation in the real world. Of course, all of these professors were tenured, so that should tell you something.
3
 

Expert Comment

by:Daniella Barion
I believe that when we study the theories, we can develop better and also discuss and bring new contributions.
2
Used Jsoup for the first time this week on trying to load in an html page and parse it.  It was really handy to use for parsing the dom.  Really cool to be able to use more CSS like selectors to do what I needed.

https://jsoup.org/
5
 
LVL 7

Expert Comment

by:Brian Matis
@kyle: I love the idea of being able to share it more! But I don't understand the "convert to article" idea... Isn't this a little short for an article?
0
 
LVL 17

Expert Comment

by:Kyle Santos
It is if you're following Jeff.
0
Ever write code that you look at, and think "no language should let me do this".


private void createURLButtonAction() throws Exception
      {
            m_view.m_loadURLButton.setOnAction(e -> {
                  try{
                        loadURL(m_view.m_urlField.getText());
                  }
                  catch (Exception exception)
                  {
                        
                  }
            });
      }
0
 
LVL 17

Expert Comment

by:Kyle Santos
*plane flies over my head*
2
 
LVL 9

Expert Comment

by:James Bilous
*no framework
Don't blame the lambdas
0
Do you think endorsements will be well moderated?
2
 
LVL 17

Expert Comment

by:Kyle Santos
*downvote*

:3
0
 
LVL 7

Expert Comment

by:Craig Kehler
Sure, but in this case I can just walk out my office door and "moderate" the user personally :P
2

Java

99K

Solutions

32K

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.