11 | num == Integer.parseInt(str) is going to faster than str.equals("" + num)str.equals("" + num) will first convert num to string which is O(n) where n being the number of digits in the number. Then it will do a string concatenation again O(n) and then finally do the string comparison. String comparison in this case will be another O(n) - n being the number of digits in the number. So in all ~3*O(n)num == Integer.parseInt(str) will convert the string to integer which is O(n) again where n being the number of digits in the number. And then integer comparison is O(1). So just ~1*O(n)To summarize both are O(n) - but str.equals("" + num) has a higher constant and so is slower. |
Wednesday, November 23, 2016
Java: Comparing ints and Strings
Tuesday, November 22, 2016
Dependency Injection (or sometime called wiring)
Every java based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while doing unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and same time keeping them independent.
Consider you have an application which has a text editor component and you want to provide spell checking. Your standard code would look something like this:
Here, we have removed the total control from TextEditor and kept it somewhere else (ie. XML configuration file) and the dependency ( ie. class SpellChecker) is being injected into the class TextEditor through a Class Constructor. Thus flow of control has been "inverted" by Dependency Injection (DI) because you have effectively delegated dependances to some external system.
Second method of injecting dependency is through Setter Methods of TextEditor class where we will create SpellChecker instance and this instance will be used to call setter methods to initialize TextEditor's properties.
Thus, DI exists in two major variants and following two sub-chapters will cover both of them with examples:
You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.
Consider you have an application which has a text editor component and you want to provide spell checking. Your standard code would look something like this:
public class TextEditor {What we've done here is create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario we would instead do something like this:
private SpellChecker spellChecker;
public TextEditor() {
spellChecker = new SpellChecker();
}
}
public class TextEditor {Here TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to TextEditor at the time of TextEditor instantiation and this entire procedure is controlled by the Spring Framework.
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
}
Here, we have removed the total control from TextEditor and kept it somewhere else (ie. XML configuration file) and the dependency ( ie. class SpellChecker) is being injected into the class TextEditor through a Class Constructor. Thus flow of control has been "inverted" by Dependency Injection (DI) because you have effectively delegated dependances to some external system.
Second method of injecting dependency is through Setter Methods of TextEditor class where we will create SpellChecker instance and this instance will be used to call setter methods to initialize TextEditor's properties.
Thus, DI exists in two major variants and following two sub-chapters will cover both of them with examples:
| S.N. | Dependency Injection Type & Description |
|---|---|
| 1 | Constructor-based dependency injectionConstructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class. |
| 2 | Setter-based dependency injectionSetter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. |
Friday, August 12, 2016
Java stackoverflow
Java (not to be confused with JavaScript) is a general-purpose object-oriented programming language designed to be used in conjunction with the Java Virtual Machine (JVM). "Java platform" is the name for a computing system that has installed tools for developing and running Java programs. Use this tag for questions referring to Java programming language or Java platform tools. (Note that Java is not to be confused with JavaScript)
Java is a high-level, platform-independent, object-oriented programming language and run-time environment. The Java language derives much of its syntax from c and c++, but its object model is simpler than that of c++ and it has fewer low-level facilities. Java applications are typically compiled to bytecode (called class files) that can be executed by a jvm(Java Virtual Machine), independent of computer architecture. The JVM often further compiles code to native machine code to optimize performance.
The JVM manages memory with the help of a garbage collector (see garbage-collection) in order to handle object removal from memory when objects are no longer in use. Java's typing discipline is static, strong, safe, nominative, and manifest. Java supports features such as reflection and interfacing with c and c++ via jni.
java is designed to have as few implementation dependencies as possible, intended to allow application developers to "write once, run anywhere" (WORA): code that executes on one platform does not need to be recompiled to run on another machine. Java was originally developed by James Gosling at Sun Microsystems (which merged with Oracle Corporation on April 20, 2009) and was released in 1995 as a core component of Sun Microsystems' Java platform.
The Java platform is the name given by Sun (now Oracle) to computing systems that have installed tools for developing and running Java programs. The platform features a wide variety of tools that can help developers work efficiently with the Java programming language.
The platform consists of two essential software packages:
- the Java Runtime Environment (JRE), which is needed to run Java applications and applets; and,
- the Java Development Kit (JDK), which is needed to develop Java applications and applets. The JDK comes with a JRE.
Background
The main reference implementation of Java is open source (the OpenJDK) and is supported by major companies including Oracle, Apple, SAP, and IBM.Very few computers can run Java programs directly. Therefore, the Java environment is normally made available by installing a suitable software component. On Windows computers, this is usually done by downloading the free Java Runtime Environment (JRE) from java.com. On Macintosh computers, the user is prompted to download Java when an application requiring it is started. On linux-like systems, Java is typically installed via the package manager.
Developers frequently need additional tools, which are available in the free Java Development Kit, which for Windows and Mac must be downloaded from Oracle and installed manually.
Java is compiled into bytecode, which is compiled by the JVM into native machine code. The compilation is done just-in-time (JIT). This was initially viewed as a performance hit, but JVM and JIT compilation improvements have made this less of a concern. In some cases, the JVM may even be faster than native code compiled to target an older version of a processor for backward-compatibility reasons.
Note: Other vendors exist, though almost all have license fees. For linux and other platforms, consult the operating system documentation.
Versions
Notable Java versions, code names, and release dates include:JDK 1.0 (January 23, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 [Playground] (December 8, 1998)
J2SE 1.3 [Kestrel] (May 8, 2000)
J2SE 1.4 [Merlin] (February 6, 2002)
J2SE 5.0 [Tiger] (September 30, 2004)
Java SE 6 [Mustang] (December 11, 2006)
Java SE 7 [Dolphin] (July 28, 2011)
Java SE 8 [JSR 337] (March 18, 2014)
Java SE 9 [TBD ] (the release has been planned for March 2017)Latest Stable Versions:Java Standard Edition 8 Update 102 (1.8.0_102) - (July 19, 2016)
Java Standard Edition 7 Update 80 (1.7.0_80) - (April 14, 2015)For more code names and release dates, visit J2SE Code Names. To see release notes for each version of the JDK, visit the Wikipedia article on Java version history.Java SE 8 is now released and is available for download.
The End Of Public Updates (Formerly called End Of Life) dates for the freely available distribution from Oracle are:
J2SE 1.4 - Oct 2008
J2SE 5.0 - Oct 2009
Java SE 6 - Feb 2013
Java SE 7 - Apr 2015
Java SE 8 - Sep 2017Initial help
New to Java or need help to get your first Java program running? See the Oracle Java Tutorials section on Getting Started.Before asking a question, please use the search box in the upper-right corner to see if it has been asked before (we have many duplicates), and read the Writing the perfect question article to learn how to get Jon Skeet to answer your question.
Naming conventions
Java programs should adhere to the following naming conventions to increase readability and decrease chances of accidental errors. By following these naming conventions, you will make it easier for others to understand your code and help you.- Type names (classes, interfaces, enums, etc.) should begin with a capital letter, and capitalize the first letter of each subsequent word. Examples include:
String,ThreadLocal, andNullPointerException. This is sometimes known as pascal case. - Method names should be camelCased; that is, they should begin with a lowercase letter and capitalize the first letter of each subsequent word. Examples:
indexOf,printStackTrace,interrupt. - Field names should be camelCased just like method names.
- Constant expression names (
static finalimmutable objects) should be written in ALL_CAPS, with underscores separating each word. Examples:YELLOW,DO_NOTHING_ON_CLOSE. This also applies to values of anEnumclass. However,static finalreferences to non-immutable objects should be camelCased.
Hello World - Your first program
Code of a typical Hello World program:public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Compilation and invocation of Hello World program:javac -d . HelloWorld.java
java -cp . HelloWorldJava source code is compiled to an intermediate form (bytecode instructions for the Java Virtual Machine) which can be executed with the java command later on.More information:
- Wikipedia on Java
- Wikipedia on the JDK
- Wikipedia on the JRE
- Download Java from Oracle
- Stackoverflow Documentation
Useful IDEs for Java
- Eclipse IDE
- Run Java code online
- NetBeans IDE
- IntelliJ IDEA
- Spring Tool Suite (based on Eclipse, includes tools for working with spring)
- JDeveloper IDE
- Android Studio (based on IntelliJ IDEA, mainly intended for working on
android projects)
- BlueJ
Beginners' resources
- The Java Tutorials - Starts from scratch on Windows/Linux/Mac and covers most of the standard library. The Java Keyword Reference listing by Oracle complements the Java Tutorials very well.
- Generics
- Coding Bat (Java) - After learning some basics, refine and hone your Java skills with Coding Bat.
- Code Conventions for the Java Programming Language
- Stanford Video Lectures on Java
- Udemy free course on Java
- Edx course on Introduction to computing with Java
Day-to-day updated resources
Advanced resources
- Java Language and Virtual Machine Specifications
- Other languages that can be mixed with Java on JVM
- A Guide to Java 8
- The Definitive Java Generics Advanced FAQ by Angelika Langer
Java frameworks, libraries, and software
Free Java programming books and resources
- Java Application Development on Linux by Carl Albing and Michael Schwarz (PDF)
- How to Think Like a Computer Scientist
- Spring IO Guides
- The Java EE 7 Tutorial (PDF)
- Java Thin-Client Programming
- Oracle's Java Tutorials
- Thinking in Java
- Effective Java (PDF)
- OSGi in Practice (PDF)
- Category wise tutorials - J2EE
- Java Example Codes and Tutorials - J2EE
- Java Design Pattern Video Training
- Code Search for Java examples
- Global Java cross-reference engine
- Java 101 Tutorials
Frequently Asked Questions
People often ask about the following Java topics:General:
Classpath:
String, StringBuilder and toString:- How do I compare strings in Java?
- Difference between StringBuilder and StringBuffer
- Why do I get
SomeType@2f92e0f4when I print my object? - Immutability of Strings in Java
equals and hashCode:Java Platform SE API:
- Skipping
nextLine()after usenextInt() - Comparing dates
- Removing items while iterating through a Collection, avoiding ConcurrentModificationException
- How to sort a
Map<Key,Value>on the values in Java? - When to use
LinkedListoverArrayList? Arrays.asList()- Differences between
HashMapandHashtable? - Difference between Set and List?
- What does the
<E>in Java mean? - Is
List<Dog>a subclass ofList<Animal>? Why aren't Java's generics implicitly polymorphic (and why aren't collections covariant)? - Java Generics: What is PECS?
- What is a raw type and why shouldn't we use it?
- How to create a generic array?
- Is Java pass by reference?
- What's the advantage of a Java enum versus a class with public static final fields?
- Difference between public, protected, private and default
- Why can't I print a double correctly?
- Division of integers returns 0
- Java's +=, -=, *=, /= compound assignment operators
- What is a stack trace, and how can I use it to debug my application errors?
- What is a
NullPointerExceptionand how do I fix it? - What is an
ArrayIndexOutOfBoundsExceptionand how do I prevent it? - How do I avoid null checks?
- Why am I getting a
NoClassDefFoundError? - Why am I getting a
NoSuchMethodError?
Thread and multithreading:- What does
java.lang.Thread.interrupt()do? - While loop doesn't see a changed value unless there's a print statement in it
implements Runnablevs.extends Thread
(Editors, please only list questions which actually are frequently asked.)
Chat rooms
Code Language (used for syntax highlighting): lang-java
Monday, August 8, 2016
JSP Hello World Example using Eclipse IDE and Tomcat web server
This simple tutorial describes how you can print "Hello World!" string in your browser by writing a simple JSP (Java server pages) program developed using eclipse IDE.
Technologies used in this article :
- Eclipse 3.7
- Tomcat
1. Create Dynamic Web Project
Select from the menu File --> New --> Dynamic Web Project.
Enter "HelloWorldJSP" as the project name. Keep rest of the settings as it is as shown in the following screenshot.
Click "Next" button.
Click "Next" button.
Check 'Generate web.xml deployment descriptor' checkbox and click "Finish" button and Eclipse IDE will generate the web project automatically as shown below
2. Create Jsp page
Right click on 'WebContent' folder and select from context menu New --> Jsp File.
Write "helloWorld.jsp" in the 'File Name' field and Click "Finish" button.
Eclipse will generate a jsp page and open the same in the JSP editor as shown below
File: helloWorld.jsp1 2 3 4 5 6 7 8 9 10 11 12 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body></body></html> |
4. Write JSP Code
Edit the generated 'helloWorld.jsp' as per the following code.
File: helloWorld.jsp1 2 3 4 5 6 7 8 9 10 11 12 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Hello World - JSP tutorial</title></head><body> <%= "Hello World!" %></body></html> |
5. Run Your Code
Right click on 'helloWorld.jsp' and select from context menu 'Run As' --> 'Run on Server'.
Select the existing tomcat server. If not available then manually define a new web server.
Click "Finish" button. HelloWorldJSP web application will be deployed in the tomcat web server.
6. Browser Output
Eclipse will open a browser and your server side jsp code will print 'Hello World!' in the browser.
Subscribe to:
Comments (Atom)