background preloader

JAVA

Facebook Twitter

Java Enum Tutorial: 10 Examples of Enum in Java. What is Enum in Java Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. One of the common use of Enum which emerged in recent years is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety and Serialization automatically.

By the way, Java Enum as type is more suitable to represent well known fixed set of things and state, for example representing state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(Enum) was not originally available in Java though it was available in other language like C and C++ but eventually Java realized and introduced Enum on JDK 5 (Tiger) by keyword Enum.

Case PENNY: Write a program to generate all possible subsets. Splitting a string into n-length chunks in Java. Regex - Split string to equal length substrings in Java. Language agnostic - Generate list of all possible permutations of a string. How can I add a String to an ArrayList in Java. How to insert Space after every Character of an existing String in Java. 10 example of using ArrayList in Java >>> Java ArrayList Tutorial. ArrayList in Java is most frequently used collection class after HashMap in Java. Java ArrayList represents an automatic re-sizable array and used in place of array. Since we can not modify size of an array after creating it, we prefer to use ArrayList in Java which re-size itself automatically once it gets full. ArrayList in Java implements List interface and allow null. Java ArrayList also maintains insertion order of elements and allows duplicates opposite to any Set implementation which doesn't allow duplicates.

ArrayList has been modified in Java5 (Tiger) to support Generics which makes Java ArrayList even more powerful because of enhanced type-safety. It’s also important to remember that ArrayList is not synchronized and should not be shared between multiple threads. Example of ArrayList in Java Let's see some example of creating ArrayList in java and using them, I have tried to provide as much example as possible to illustrate different operations possible on Java ArrayList. Types - Converting int to char in java. Convert String to Int,Convert String to Int Java,Java Convert String to Int,Java Convert String to Integer,Java Convert String Int. Java stack trace - How to print a stack trace to debug Java exceptions. By Alvin Alexander. Last updated: Sep 16, 2013 Java stack trace FAQ: How can I print a Java stack trace to debug an exception?

Many times when you generate an exception in a Java program, you just print the exception to standard output, using a code sequence like the one shown in Listing 1. I typically see this done when developers are debugging Java programs. Listing 1 (above): This snippet of Java code shows how to print the message of an exception, using Java's getMessage() method. Again, you probably don't handle your errors like this in a live Java application, but you might do it during the development and debugging process.

Here's the output you'd get from the println statement above if a program using this code snippet tried to open a file named fred.txt, and the file didn't exist: Got an IOException: fred.txt Creating a better error message for debugging: e.printStackTrace() Using this code snippet when trying to open a non-existent file named fred.txt, you'll get this output message: Optimization - Most efficient way of converting String to Integer in java. Int vs Integer. Newbies are often confused by the difference between int and Integer, boolean vs Boolean, char vs Character, short vs Short, long vs Long, float vs Float or double vs Double. To properly understand the difference, you should read an introductory textbook on Java.

I will make a small stab at answering here. Everything I say here applies analogously to char and Character, short and Short, long and Long, float and Float, double and Double. Definitions An int is a primitive. It is not an Object. An Integer, is a Object that contains a single int field. Which is better? That is like asking which is better a volley ball or a volleyball in a Fedex box.

Converting Fortunately it is easy to convert back and forth between int and Integer. int i = ii.intValue(); Integer ii = new Integer( i ); See this Amanuensis for other conversions. Why Both? Why are there both int and Integer? Learning More. Getting Error java.lang.NumberFormatException: For input string: "16.0"

Java - Why does int num = Integer.getInteger("123") throw NullPointerException. Java Vector,Using Vectors in Java,Vector Object in Java,Online Java Vector Example. Learning Java - Chapter 10 : Java. In the discussion of Vector we mentioned the Enumeration class, which provides for stepping through the elements of a list such as a Vector. However, Iterator, introduced with Java 1.2, is now preferred to Enumeration. Iterator differs from Enumeration in 2 ways: Elements can be safely removed from Vector using the remove (int index) without causing the Iterator to fail..

The hasMore () and next () methods in Iterator are short and direct as opposed to the corresponding long and boring methods nextElement () and hasMoreElements () in Enumeration. All the old container classes were retro-fitted with the Java 1.2 release to support the Iterator interface and the new container classes added in JDK 1.2 with the Collections Framework support only the Iterator interface. The syntax for iterating over the elements in a Vector is as follows Vector vec = new Vector; // Populate it...

Again, we retrieve Object types from the Iterator. // Build an ArrayList and populate it with integers from 0 to 19. Delete all rows from a table : Delete « Insert Update Delete « Oracle PL/SQL Tutorial. Jdbc Insert Statement. Java foreach loop. Vector example in Java. Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the collections framework. With the release of Java 2, Vector was reengineered to extend AbstractList and implement the List interface, so it now is fully compatible with collections. Here are the Vector constructors: Vector( ) Vector(int size) Vector(int size, int incr) Vector(Collection c) The first form creates a default vector, which has an initial size of 10.

All vectors start with an initial capacity. Vector defines these protected data members: int capacityIncrement; int elementCount; Object elementData[ ]; The increment value is stored in capacityIncrement. Because Vector implements List, you can use a vector just like you use an ArrayList instance. The following program uses a vector to store various types of numeric objects. The output from this program is shown here: Vector or ArrayList -- which is better? Q: Vector or ArrayList -- which is better and why? A: Sometimes Vector is better; sometimes ArrayList is better; sometimes you don't want to use either. I hope you weren't looking for an easy answer because the answer depends upon what you are doing. There are four factors to consider: APISynchronizationData growthUsage patterns Let's explore each in turn.

In The Java Programming Language (Addison-Wesley, June 2000) Ken Arnold, James Gosling, and David Holmes describe the Vector as an analog to the ArrayList. So, from an API perspective, the two classes are very similar. Synchronization Vectors are synchronized. Data growth Internally, both the ArrayList and Vector hold onto their contents using an Array. Usage patterns Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container.

Learn more about this topic. Difference between elementAt(int x) and get(int x) 5 Best Core Java Books you must read as a developer. Looking for best java books? We have short listed some of the highly recommended Java books for beginners and senior experienced programmers. The core java books may help you easily thrive as a Java developer. The job of a Java developer is to write efficient programs to solve critical business problems. Some of these are core java books, whereas other books focus on a some of the advanced topics in Java programming. If you want success in Java, you do not need to enroll in a class. You could save a lot of money by simply reading a good Java book. When you refer to a good JAVA book, you are also more likely to get detailed and current information than you would from a teacher or from self-education since good JAVA books are written by authorities in the field, authorities with years of experience in JAVA coding and an educational background in the same.

The fact that there are many options available is also a big plus. Thinking in Java (By: Bruce Eckel) (By: Joshua Bloch , Neal Gafter) Java Examples - Learn Java by Examples. Wrong Time with System.currentTimeMillis () (Java) Java System.currentTimeMillis() Java: Multiple class declarations in one file. Formatter (Java 2 Platform SE 5.0) Java.lang.Object java.util.Formatter All Implemented Interfaces: Closeable, Flushable public final class Formatterextends Objectimplements Closeable, Flushable An interpreter for printf-style format strings. Formatters are not necessarily safe for multithreaded access. Formatted printing for the Java language is heavily inspired by C's printf. Examples of expected usage: StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); // Explicit argument indices may be used to re-order output. formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") // -> " d c b a" // Optional locale as the first argument can be used to get // locale-specific formatting of numbers.

Convenience methods for common formatting requests exist as illustrated by the following invocations: // Writes a formatted string to System.out. Like C's sprintf(3), Strings may be formatted using the static method String.format: Organization Summary. Command line - Java println formatting so I can display a table. Java - Math.random() versus Random.nextInt(int) Scanner (Java Platform SE 6) Java.lang.Object java.util.Scanner All Implemented Interfaces: Iterator<String> public final class Scannerextends Objectimplements Iterator<String> A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

The resulting tokens may then be converted into values of different types using the various next methods. For example, this code allows a user to read a number from System.in: Scanner sc = new Scanner(System.in); int i = sc.nextInt(); As another example, this code allows long types to be assigned from entries in a file myNumbers: Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); } The scanner can also use delimiters other than whitespace.

Prints the following output: 1 2 red blue The same output can be generated with this code, which uses a regular expression to parse all four tokens at once: Number syntax. Lesson 1: Hello World. This Java video lesson demonstrates how to write, compile, and run a simple Java program that outputs the message "Hello World! " For this lesson, you need to have the NetBeans IDE and the JDK installed as we showed in Java Lesson 0 To start, you should have the NetBeans IDE open. Then left-click File in the menubar and left-click New Project in the submenu.

This will open the "New Project" dialog. By default, it should appear as it does below. If not, left-click Java under "Categories:" and left-click Java Application under "Projects:" in the "New Project" panes shown here. These are the basic steps involved in creating and running a simple program.