How do you make websites with Java?

Question This might be a really trivial question, but I’ve been writing Java programs at my school and I just found out that I can create websites with Java as well. How can I do that? Any good books/tutorials for that? Which is better for Web development, Java or PHP? Also, when using PHP, MySQL… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

is there a ‘block until condition becomes true’ function in java?

Question I’m writing a listener thread for a server, and at the moment I’m using: while (true){ try { if (condition){ //do something condition=false; } sleep(1000); } catch (InterruptedException ex){ Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex); } } With the code above, I’m running into issues with the run function eating all the cpu time looping. The sleep… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to capture arguments passed to a Groovy script?

Question I am just starting out with Groovy. I couldn’t find any examples anywhere of how to handle arguments to a Groovy script and so I hacked this method myself. There must be a better way of doing this? If so, I am looking for this better way, since I am probably overlooking the obvious.… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to exit an Android app programmatically?

Question I am sure this question has been asked number of times because I read a few. My client wants me to put a button into his app where users can click and exit. I have read this and found calling finish() will do it. But, finish is only closing the current running activity right?… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to make a JAR file that includes DLL files?

Question I bought a third-party Java library which includes a JAR file and two DLL files. I wrote my own Java program which invoke the third-party JAR file. Now my question is how can I package all my code into a single JAR file which include all my code and the third-party JAR and DLLs?… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Blocking queue and multi-threaded consumer, how to know when to stop

Question I have a single thread producer which creates some task objects which are then added into an ArrayBlockingQueue (which is of fixed size). I also start a multi-threaded consumer. This is build as a fixed thread pool (Executors.newFixedThreadPool(threadCount);). I then submit some ConsumerWorker intances to this threadPool, each ConsumerWorker having a refference to the… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to change value of ArrayList element in java

Question Please help me with below code , I get the same output even after changing the value import java.util.*; class Test { public static void main(String[] args) { ArrayList<Integer> a = new ArrayList<Integer>(); // added 0-9 to ArrayList for(int i=0;i<9;i++) a.add(new Integer(i)); // initialize the Iterator Iterator<Integer> i = a.iterator(); // changed the value… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What’s the C++ version of Java’s ArrayList

Question Just getting back into using C++ and trying to convert a simple Java program I wrote recently. What’s the preferred equivalent to the Java ArrayList in C++? Solution Use the std::vector class from the standard library. SLaksSLaks

Share this article:
Follow us on Twitter Follow us on Facebook

Is there an equivalent of Scala’s Either in Java 8?

Question Just like java.util.Optional<T> in Java 8 is (somewhat) equivalent to Scala’s Option[T] type, is there an equivalent to Scala’s Either[L, R]? Solution There is no Either type is Java 8, so you need to create one yourself or use some third-party library. You may build such a feature using the new Optional type (but read… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Tomcat 7: How to set initial heap size correctly?

Question I was trying to adjust initial heap size of a tomcat 7 (CentOS, java -version: 1.6.0_25-b06) instance by adding the following line to catalina.sh: export CATALINA_OPTS=”-Xms=512M -Xmx=1024M” Starting up tomcat fails and logs the following message to catalina.out: Invalid initial heap size: -Xms=512m Could not create the Java virtual machine. What is wrong with… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Sorting a list with stream.sorted() in Java

Question I’m interested in sorting a list from a stream. This is the code I’m using: list.stream() .sorted((o1, o2)->o1.getItem().getValue().compareTo(o2.getItem().getValue())) .collect(Collectors.toList()); Am I missing something? The list is not sorting. It should sort the lists according to the item with the lowest value. for (int i = 0; i < list.size(); i++) { System.out.println(“list ” +… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

best way to pick a random subset from a collection?

Question I have a set of objects in a Vector from which I’d like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution: Vector itemsVector = getItems(); Collections.shuffle(itemsVector); itemsVector.setSize(5); While this has the advantage of… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Why can’t enum constructors be protected or public in Java?

Question The whole question is in the title. For example: enum enumTest { TYPE1(4.5, “string1”), TYPE2(2.79, “string2”); double num; String st; enumTest(double num, String st) { this.num = num; this.st = st; } } The constructor is fine with the default or private modifier, but gives me a compiler error if given the public or… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java converting Image to BufferedImage

Question There is already question like this link on StackOverflow and the accepted answer is “casting”: Image image = ImageIO.read(new File(file)); BufferedImage buffered = (BufferedImage) image; In my program I try: final float FACTOR = 4f; BufferedImage img = ImageIO.read(new File(“graphic.png”)); int scaleX = (int) (img.getWidth() * FACTOR); int scaleY = (int) (img.getHeight() * FACTOR);… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What’s the difference between HashSet and Set?

Question Saw the code snippet like Set<Record> instances = new HashSet<Record>(); I am wondering if Hashset is a special kind of set. Any difference between them? Solution A Set represents a generic “set of values”. A TreeSet is a set where the elements are sorted (and thus ordered), a HashSet is a set where the… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java, reading a file from current directory?

Question I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run). In other words, if the user specifies the file name to be “myFile.txt”, and that file is already in the current directory: reader = new BufferedReader(new FileReader(“myFile.txt”)); does not work.… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to unescape a Java string literal in Java?

Question I’m processing some Java source code using Java. I’m extracting the string literals and feeding them to a function taking a String. The problem is that I need to pass the unescaped version of the String to the function (i.e. this means converting n to a newline, and \ to a single , etc).… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Remove part of string in Java

Question I want to remove a part of string from one character, that is: Source string: manchester united (with nice players) Target string: manchester united Solution There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class.… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Why is there no sub-class visibility modifier in Java?

Question On more than one occasion I have found myself desiring a variable visibility that is not possible in Java. I wanted certain members to be visible within their own class and within any sub-classes, but not to the rest of the package or to the rest of the world. In other words, I wanted… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How does ApplicationContextAware work in Spring?

Question In spring, if a bean implements ApplicationContextAware, then it is able to access the applicationContext. Therefore it is able to get other beans. e.g. public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; } public static ApplicationContext getApplicationContext() { return applicationContext; } }… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What does the @Valid annotation indicate in Spring?

Question In the following example, the ScriptFile parameter is marked with an @Valid annotation. What does @Valid annotation do? @RequestMapping(value = “/scriptfile”, method = RequestMethod.POST) public String create(@Valid ScriptFile scriptFile, BindingResult result, ModelMap modelMap) { if (scriptFile == null) throw new IllegalArgumentException(“A scriptFile is required”); if (result.hasErrors()) { modelMap.addAttribute(“scriptFile”, scriptFile); modelMap.addAttribute(“showcases”, ShowCase.findAllShowCases()); return “scriptfile/create”; }… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Sending GET request with Authentication headers using restTemplate

Question I need to retrieve a resources from my server by sending a GET request with the some Authorization headers using RestTemplate. After going over the docs I noticed that none of the GET methods accept headers as a parameter, and the only way to send Headers such as accept and Authorization is by using… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to register Spring @Configuration annotated class instead of applicationContext.xml file in web.xml?

Question I am using jsf and spring together in web application. I have configured datasource and session factory in one configuration class which uses annotations like @Configuration, @ComponentScan etc. I don’t have any applicationContext.xml file in my project as I am handling every entry of context xml in Configuration class. The test case works successfully… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Is it possible to disable jsessionid in tomcat servlet?

Question Is it possible to turnoff jsessionid in the url in tomcat? the jsessionid seems not too search engine friendly. Solution You can disable for just search engines using this filter, but I’d advise using it for all responses as it’s worse than just search engine unfriendly. It exposes the session ID which can be… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java equivalent of PHP’s implode(‘,’ , array_filter( array () ))

Question I often use this piece of code in PHP $ordine[‘address’] = implode(‘, ‘, array_filter(array($cliente[‘cap’], $cliente[‘citta’] ,$cliente[‘provincia’]))); It clears empty strings and join them with a “,”. If only one remains it doesn’t add an extra unneeded comma. It doesn’t add a comma at the end. If none remains it returns empty string. Thus I… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Varargs Java Ambiguous Call

Question I’m a little confused about Java’s varargs methods: public static int sum(int …a) { return 0; } public static double sum(double …a) { return 0.0; } When I tried to invoke sum() without passing any argument, then the int version of method was invoked. I don’t understand why; normally the compiler must raise an… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

New Integer vs valueOf

Question I was using Sonar to make my code cleaner, and it pointed out that I’m using new Integer(1) instead of Integer.valueOf(1). Because it seems that valueOf does not instantiate a new object so is more memory-friendly. How can valueOf not instantiate a new object? How does it work? Is this true for all integers?… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to use Maven pom to download jar files only to a specific directory?

Question Is there a way to download dependencies from a pom.xml file to a specified folder in java? I’m able to run maven command from java and I got download messages, but I don’t know where maven stores these libraries? How can I download these dependencies to a specific folder? Solution Take a look at… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to redirect verbose garbage collection output to a file?

Question How do I redirect verbose garbage collection output to a file? Sun’s website shows an example for Unix but it doesn’t work for Windows. Solution From the output of java -X: -Xloggc:<file> log GC status to a file with time stamps Documented here: -Xloggc:filename Sets the file to which verbose GC events information should… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Two dimensional array initializer followed by square brackets

Question I have a problem understanding this piece of code: int[] it = new int[][]{{1}}[0]; Why is it compileable, and how can I understand such a declaration? Solution What you are doing here is: Declaring a new variable int[] it (which is a one-dimensional array) Assigning its value from the first element [0] of the… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What is the difference between a variable, object, and reference?

Question Exactly what are the differences between variables, objects, and references? For example: they all point to some type, and they must all hold values (unless of course you have the temporary null-able type), but precisely how are their functions and implementations different from each other? Example: Dog myDog = new Dog(); //variable myDog that… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Detecting a long press with Android

Question I am currently using onTouchEvent(MotionEvent event){ } to detect when the user presses my glSurfaceView is there a way to detect when a long click is made. I’m guessing if I can’t find much in the dev docs then it will be some sort of work around method. Something like registering ACTION_DOWN and seeing… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What does the term Plain Old Java Object (POJO) exactly mean?

Question What does the term Plain Old Java Object (POJO) mean? I couldn’t find anything explanatory enough. POJO’s Wikipedia page says that POJO is an ordinary Java Object and not a special object. Now, what makes or what doesn’t make and object special in Java? The above page also says that a POJO should not… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Converting List to String[] in Java

Question How do I convert a list of String into an array? The following code returns an error. public static void main(String[] args) { List<String> strlist = new ArrayList<String>(); strlist.add(“sdfs1”); strlist.add(“sdfs2”); String[] strarray = (String[]) strlist.toArray(); System.out.println(strarray); } Error: Exception in thread “main” java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; at test.main(test.java:10) Solution You want… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

IntelliJ: Generate switch case

Question Is there really no way to generate a switch case for a given variable in IntelliJ? Ctrl+Space as well as Ctrl+J yield no results. Solution For enum variables, enter switch (myEnumVar) and press Alt+Enter. Smart completion will suggest: Create missing ‘switch’ branches Crazy Coder provided the following screenshot showing how to enable the Create… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to deserialize a class with overloaded constructors using JsonCreator

Question I am trying to deserialize an instance of this class using Jackson 1.9.10: public class Person { @JsonCreator public Person(@JsonProperty(“name”) String name, @JsonProperty(“age”) int age) { // … person with both name and age } @JsonCreator public Person(@JsonProperty(“name”) String name) { // … person with just a name } } When I try this… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to get distinct results in hibernate with joins and row-based limiting (paging)?

Question I’m trying to implement paging using row-based limiting (for example: setFirstResult(5) and setMaxResults(10)) on a Hibernate Criteria query that has joins to other tables. Understandably, data is getting cut off randomly; and the reason for that is explained here. As a solution, the page suggests using a “second sql select” instead of a join.… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Regex for converting CamelCase to camel_case in java

Question I understand why the desired output is not given for converting using regex a string like FooBar to Foo_Bar which instead gives Foo_Bar_. I could have done something with String.substring substring(0, string.length() – 2) or just replaced the last character, but I think there is a better solution to such a scenario. Here is… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Is this a JVM bug or “expected behavior”?

Question I noticed some unexpected behavior (unexpected relative to my personal expectations), and I’m wondering if something if there is a bug in the JVM or if perhaps this is a fringe case where I don’t understand some of the details of what exactly is supposed to happen. Suppose we had the following code in… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Very confused by Java 8 Comparator type inference

Question I’ve been looking at the difference between Collections.sort and list.sort, specifically regarding using the Comparator static methods and whether param types are required in the lambda expressions. Before we start, I know I could use method references, e.g. Song::getTitle to overcome my problems, but my query here is not so much something I want… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to pass a type as a method parameter in Java

Question In Java, how can you pass a type as a parameter (or declare as a variable)? I don’t want to pass an instance of the type but the type itself (eg. int, String, etc). In C#, I can do this: private void foo(Type t) { if (t == typeof(String)) { … } else if… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What is the best way to generate a unique and short file name in Java

Question I don’t necessarily want to use UUIDs since they are fairly long. The file just needs to be unique within its directory. One thought which comes to mind is to use File.createTempFile(String prefix, String suffix), but that seems wrong because the file is not temporary. The case of two files created in the same… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you’re running

Question Installed Android Studio 2.2 Preview 2 and getting this error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you’re running. Check your computer’s system information and then contact the software publisher Screenshot: I re-installed the JDK, still same issue. I even tried to use the embedded JDK but… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Integer to two digits hex in Java

Question I need to change a integer value into 2-digit hex value in Java.Is there any way for this. Thanks My biggest number will be 63 and smallest will be 0. I want a leading zero for small values. Solution String.format(“%02X”, value); If you use X instead of x as suggested by aristar, then you… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Iterate an Enumeration in Java 8

Question Is it possible to iterate an Enumeration by using Lambda Expression? What will be the Lambda representation of the following code snippet: Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); while (nets.hasMoreElements()) { NetworkInterface networkInterface = nets.nextElement(); } I didn’t find any stream within it. Solution In case you don’t like the fact that Collections.list(Enumeration) copies the entire… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do I parse JSON from a Java HTTPResponse?

Question I have an HttpResponse object for a web request I just made. The response is in the JSON format, so I need to parse it. I can do it in an absurdly complex way, but it seems like there must be a better way. Is this really the best I can do? HttpResponse response;… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Adding to the classpath on OSX

Question Can anyone tell me how to add to the classpath on OSX? Solution If you want to make a certain set of JAR files (or .class files) available to every Java application on the machine, then your best bet is to add those files to /Library/Java/Extensions. Or, if you want to do it for… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Why can a class not be defined as protected?

Question I know this is a stupid question, but I still have a doubt which needs to be cleared. My question is, why can we not define a class as protected? I know that we can’t, but why? There should be some specific reason. Solution Because it makes no sense. Protected class member (method or… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

how to disable spring boot logo in stdout?

Question Is there a way to disable the lovely but very visible ASCII Spring boot logo : . ____ _ __ _ _ /\ / ___’_ __ _ _(_)_ __ __ _ ( ( )___ | ‘_ | ‘_| | ‘_ / _` | \/ ___)| |_)| | | | | || (_| | )… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Error:Execution failed for task ‘:app:dexDebug’. com.android.ide.common.process.ProcessException

Question Error:Execution failed for task ‘:app:dexDebug’. com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:Program FilesJavajdk1.8.0_40binjava.exe” finished with non-zero exit value 2 I searched all the similar questions and solutions, but they do not help. I hope experts like you come up. The project code has been uploaded into bitbucket: https://tainule@bitbucket.org/tainule/numad-huizhang.git I have two modules, app and endpoint. Below… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Why can’t your switch statement data type be long, Java?

Question Here’s an excerpt from Sun’s Java tutorials: A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that “wrap” certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects). There must be… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Any good examples of inheriting from a concrete class?

Question Background: As a Java programmer, I extensively inherit (rather: implement) from interfaces, and sometimes I design abstract base classes. However, I have never really felt the need to subclass a concrete (non-abstract) class (in the cases where I did it, it later turned out that another solution, such as delegation would have been better).… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Using Alphabetic Characters in SimpleDateFormat Pattern String

Question Is it possible to include an alphabetic character in a SimpleDateFormat Pattern String? I am trying to create a format string where the letter ‘T’ is included before the time for example: 2003-11-15T09:30:47-05:00. I am currently using yyyy-MM-ddhh:mm:ssZ as the pattern string. If I change it to yyyy-MM-ddThh:mm:ssZ it will throw an exception as… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do I check if a zero is positive or negative?

Question Is it possible to check if a float is a positive zero (0.0) or a negative zero (-0.0)? I’ve converted the float to a String and checked if the first char is a ‘-‘, but are there any other ways? Solution Yes, divide by it. 1 / +0.0f is +Infinity, but 1 / -0.0f… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to convert a Java String to an ASCII byte array?

Question How to convert a Java String to an ASCII byte array? Solution Using the getBytes method, giving it the appropriate Charset (or Charset name). Example: String s = “Hello, there.”; byte[] b = s.getBytes(StandardCharsets.US_ASCII); (Before Java 7: byte[] b = s.getBytes(“US-ASCII”);) Sebastian Paaske TørholmSebastian Paaske Tørholm

Share this article:
Follow us on Twitter Follow us on Facebook

Is there a better way to combine two string sets in java?

Question I need to combine two string sets while filtering out redundant information, this is the solution I came up with, is there a better way that anyone can suggest? Perhaps something built in that I overlooked? Didn’t have any luck with google. Set<String> oldStringSet = getOldStringSet(); Set<String> newStringSet = getNewStringSet(); for(String currentString : oldStringSet)… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Is my Android App Draining Battery?

Question I’m developing a game for Android. It uses a surface view and uses the sort of standard 2D drawing APIs provided. When I first released the game, I was doing all sorts of daft things like re-drawing 9-patches on each frame and likewise with text. I have since optimised much of this by drawing… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

does System.currentTimeMillis() return UTC time?

Question I want to get the current UTC time in millis. I searched google and got some answers that System.currentTimeMillis() does returns UTC time. but it does not. If I do following: long t1 = System.currentTimeMillis(); long t2 = new Date().getTime(); long t3 = Calendar.getInstance().getTimeInMillis(); all three times are almost same ( difference is in… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Getting unix timestamp from Date()

Question I can convert a unix timestamp to a Date() object by putting the long value into the Date() constructor. For eg: I could have it as new Date(1318762128031). But after that, how can I get back the unix timestamp from the Date() object? Solution getTime() retrieves the milliseconds since Jan 1, 1970 passed to… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to change tomcat port number

Question I am developing a web application in JSP, in that for some purpose I need to change tomcat accessing port. Is there any possibility? Solution Simple !!… you can do it easily via server.xml Go to tomcat>conf folder Edit server.xml Search “Connector port” Replace “8080” by your port number Restart tomcat server. You are… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Print the stack trace of an exception

Question How do I print the stack trace of an exception to a stream other than stderr? One way I found is to use getStackTrace() and print the entire list to the stream. Solution Throwable.printStackTrace(..) can take a PrintWriter or PrintStream argument: } catch (Exception ex) { ex.printStackTrace(new java.io.PrintStream(yourOutputStream)); } That said, consider using a… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to round up integer division and have int result in Java?

Question I just wrote a tiny method to count the number of pages for cell phone SMS. I didn’t have the option to round up using Math.ceil, and honestly it seems to be very ugly. Here is my code: public class Main { /** * @param args the command line arguments */ public static void… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Overriding vs Hiding Java – Confused

Question I’m confused on how Overriding differs from Hiding in Java. Can anyone provide more details on how these differ? I read the Java Tutorial but the sample code still left me confused. To be more clear, I understand Overriding well. My issue is that I don’t see that hiding is any different except for… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Intellij (Android studio) member variable prefix

Question How do I configure Android Studio (or Intellij generally) to correctly generate getters and setters for member variables with prefixes? If I have a class public class Foo{ int mBar; } I want it to create getBar() instead of getMBar when I do Refactor->Encapsulate or Generate EDIT I found the way to do it… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Why do Java people frequently consume exceptions silently?

Question I never did any serious Java coding before, but I learned the syntax, libraries, and concepts based on my existing skills (Delphi & C#). One thing I hardly understand is that I’ve seen so much code that silently consume exceptions after printStackTrace like this: public void process() { try { System.out.println(“test”); } catch(Exception e)… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What Java XML library do you recommend (to replace dom4j)?

Question I’m looking for something like dom4j, but without dom4j’s warts, such as bad or missing documentation and seemingly stalled development status. Background: I’ve been using and advocating dom4j, but don’t feel completely right about it because I know the library is far from optimal (example: see how methods in XSLT related Stylesheet class are… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Math.abs returns wrong value for Integer.Min_VALUE

Question This code: System.out.println(Math.abs(Integer.MIN_VALUE)); Returns -2147483648 Should it not return the absolute value as 2147483648 ? Solution Integer.MIN_VALUE is -2147483648, but the highest value a 32 bit integer can contain is +2147483647. Attempting to represent +2147483648 in a 32 bit int will effectively “roll over” to -2147483648. This is because, when using signed integers, the… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

(Retrofit) Could not locate converter for class crashing app

Question So Retrofit 2.0.0 was recently released and theres not really any updated examples on how to use it, but im trying to implement it for a basic API call. Im getting a java.lang.IllegalArgumentException: Unable to create converter for class` caused by Caused by: java.lang.IllegalArgumentException: Could not locate converter for class orbyt.app.dataclass. Tried: * retrofit.OkHttpBodyConverterFactory… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Why doesn’t Java allow private members in interface?

Question Why doesn’t Java allow private members in interface? Is there any particular reason? Solution From the Java Language Spec, (Access Control): “The Java programming language provides mechanisms for access control, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class.” Access control… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What exactly does “Stream” and “Buffer” mean in Java I/O?

Question I just learned about input/output using BufferedReader. I wanted to know what exactly are the meanings of the term Stream and Buffer? Also what does this line of code serves us: BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Solution Java has two kinds of classes for input and output (I/O): streams and readers/writers. Streams (InputStream, OutputStream and… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Android/Java – Date Difference in days

Question I am getting the current date (in format 12/31/1999 i.e. mm/dd/yyyy) as using the below code: Textview txtViewData; txtViewDate.setText(“Today is ” + android.text.format.DateFormat.getDateFormat(this).format(new Date())); and I am having another date in format as: 2010-08-25 (i.e. yyyy/mm/dd) , so I want to find the difference between date in number of days, how do I find… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Is it safe to call a synchronized method from another synchronized method?

Question If a synchronized method calls another synchronized method, is it thread safe? void synchronized method1() { method2() } void synchronized method2() { } Solution Yes, when you mark methods as synchronized, then you are really doing this: void method1() { synchronized (this) { method2() } } void method2() { synchronized (this) { } }… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Abstract class vs Interface in Java

Question I was asked a question, I wanted to get my answer reviewed here. Q: In which scenario it is more appropriate to extend an abstract class rather than implementing the interface(s)? A: If we are using template method design pattern. Am I correct ? I am sorry if I was not able to state… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Play! framework uses a of statics

Question Waaah, the Play! framework has so many static methods. Where I go to school, we were told never ever to use any statics, yet Play! uses it like there’s no tomorrow. Is that somehow okay? If so, why? We (7 people and I) are planning to use the Play! framework for a project involving… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Maven: How to rename the war file for the project?

Question I have a project bird with following components in pom.xml <groupId>com.myorg</groupId> <artifactId>bird</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>bird</name> <modules> <module>persistence</module> <module>business</module> <module>service</module> <module>web</module> </modules> and the web module as <parent> <artifactId>bird</artifactId> <groupId>com.myorg</groupId> <version>1.0-SNAPSHOT</version> </parent> <artifactId>web</artifactId> <packaging>war</packaging> web module creates the war file named web-1.0-SNAPSHOT.war How can I, using maven rename this to bird.war? Solution You can use… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Short IF – ELSE statement

Question I’m trying to make my code more readable, so I decided to use some short IF statements. Here’s my code which doesn’t work (“not a statement”): jXPanel6.isVisible() ? jXPanel6.setVisible(true) : jXPanel6.setVisible(false); What’s wrong with this? Needs brackets? Where? Solution The “ternary expression” x ? y : z can only be used for conditional assignment.… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Unit testing a JAX-RS Web Service?

Question I’m currently looking for ways to create automated tests for a JAX-RS (Java API for RESTful Web Services) based web service. I basically need a way to send it certain inputs and verify that I get the expected responses. I’d prefer to do this via JUnit, but I’m not sure how that can be… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What is the difference between an Observer and a Subscriber?

Question I am trying to decipher the following function: Subscription getCar(id, Observer<Car> observer) { return getCarDetails(id, new Observer<CarDetails> { @Override onNext(CarDetails details) { observer.onNext(details.getCar()); } }); } I got a good intro to rxjava from http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/ but it only mentioned Observer in passing, saying you’ll be using Subscriber most of the time to consumer items… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Unresponsive KeyListener for JFrame

Question I’m trying to implement a KeyListener for my JFrame. On the constructor, I’m using this code: System.out.println(“test”); addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { System.out.println( “tester”); } public void keyReleased(KeyEvent e) { System.out.println(“2test2”); } public void keyTyped(KeyEvent e) { System.out.println(“3test3”); } }); When I run it, the test message comes up in my… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Are defaults in JDK 8 a form of multiple inheritance in Java?

Question A new feature coming in JDK 8 allows you to add to an existing interface while preserving binary compatibility. The syntax is like public interface SomeInterface() { void existingInterface(); void newInterface() default SomeClass.defaultImplementation; } This way for all existing implementations of SomeInterface when they upgrade to this new version they don’t all suddenly have… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Is there an equivalent of java.util.regex for “glob” type patterns?

Question Is there a standard (preferably Apache Commons or similarly non-viral) library for doing “glob” type matches in Java? When I had to do similar in Perl once, I just changed all the “.” to “.“, the “*” to “.*” and the “?” to “.” and that sort of thing, but I’m wondering if somebody… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Programmatically getting the MAC of an Android device

Question I need to obtain the MAC address of my android device using Java. I’ve searched online, but I haven’t found anything useful. Solution As was already pointed out in the comment, the MAC address can be received via the WifiManager. WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo info = manager.getConnectionInfo(); String address = info.getMacAddress(); Also… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java Error opening registry key

Question I get this error when I try to do anything with Java in command prompt: Error opening registry key ‘SoftwareJavaSoftJava Runtime Environment.3’ Error: could not find Java.dll Error: could not find Java 2 Runtime Environment I did screw around with deleting Java directories and registry a few days ago. I restarted computer and java… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Understanding Java’s Reference classes: SoftReference, WeakReference, and PhantomReference

Question Can someone explain the difference between the three Reference classes (or post a link to a nice explanation)? SoftReference > WeakReference > PhantomReference, but when would I use each one? Why is there a WeakHashMap but no SoftHashMap or PhantomHashMap? And if I use the following code… WeakReference<String> ref = new WeakReference<String>(“Hello!”); if (ref… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Regex expressions in Java \s vs. \s+

Question Please, what’s the difference between those expressions x = x.replaceAll(“\s”, “”); x = x.replaceAll(“\s+”, “”); Solution The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They’re the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation): Greedy quantifiers X? X, once or… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to convert a LocalDate to an Instant?

Question I work with the new DateTime API of Java 8. How to convert a LocalDate to an Instant? I get an exception with LocalDate date = LocalDate.of(2012, 2, 2); Instant instant = Instant.from(date); and I don’t understand why. Solution In order to convert it to an instant you need to have a LocalDateTime instance,… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Why can final object be modified?

Question I came across the following code in a code base I am working on: public final class ConfigurationService { private static final ConfigurationService INSTANCE = new ConfigurationService(); private List providers; private ConfigurationService() { providers = new ArrayList(); } public static void addProvider(ConfigurationProvider provider) { INSTANCE.providers.add(provider); } … INSTANCE is declared as final. Why can… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Joining paths in Java

Question In Python I can join two paths with os.path.join: os.path.join(“foo”, “bar”) # => “foo/bar” I’m trying to achive the same in Java, without worrying if the OS is Unix, Solaris or Windows: public static void main(String[] args) { Path currentRelativePath = Paths.get(“”); String current_dir = currentRelativePath.toAbsolutePath().toString(); String filename = “data/foo.txt”; Path filepath = currentRelativePath.resolve(filename);… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Why does Collections.sort use Mergesort but Arrays.sort does not?

Question I am using JDK-8 (x64). For Arrays.sort (primitives) I found the following in the Java documentation: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch.` For Collections.sort (objects) I found this “Timsort”: This implementation is a stable, adaptive, iterative mergesort … This implementation dumps the specified list into… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java: Check if command line arguments are null

Question I am looking to do some error checking for my command line arguments public static void main(String[] args) { if(args[0] == null) { System.out.println(“Proper Usage is: java program filename”); System.exit(0); } } However, this returns an array out of bounds exception, which makes sense. I am just looking for the proper usage. Solution The… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook