Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, June 17, 2016

Debugging Applet Code

Step -1: control panel settings
  • Go to control panel -> click on Java (32-bit) as shown in the below screen:
  • Click on Tab "Java"
  • Click on button "View"
  • Under "Runtime Parameters" column paste the below parameters:-Xdebug -Xrunjdwp:transport=dt_socket,address=2503,server=y,suspend=y
  • Press "Ok" and then "Ok" button.











Step -2: Eclipse settings

  • Go to Run-> Debug Configurations
  • Right Click on "Remote Java Application" and click on "New"
  • Provide the details like: name, project, host and port(this port is what we gave in run-time parameters configuration, in our case it is 2503)
  • Click on "Apply" and "close".


Step -3: Restart Application Server

Step -4: Restart Browser

Step -5: Login to your application and try to access the applet

Step -6: Now come back to eclipse and go to "Run" and click on "Debug Configuration" we have created

Now your applet code is ready for debug.

Happy Debugging :)

Courtesy: Pradeep

Monday, November 16, 2015

RegEx: Extract tokens from a URL

String url = "http://localhost:8080/dummy/index.jsp?key1=value1&key2=value2;http://localhost:8080/dummy/index.jsp?key2=value3;";

Pattern pattern = Pattern.compile("(key2=)(.+?)(&|;)");

Matcher matcher = pattern.matcher(url);

while (matcher.find()) {
System.out.println(matcher.group(2));
}

Output:
value2
value3

Note: Usually, while creating patterns, if we are interested in groups, we categorize them in parenthesis as shown above. In our example, we have 3 groups, out of which we are interested in group-2. 

Sunday, May 4, 2014

Java Paper

  1. The static initializer block will be called on loading of the class, and will have no access to instance variables or methods. It is often used to create static variables.
  2. The non-static initializer block(anonymous block defined outside all member functions) on the other hand is created on object construction only, will have access to instance variables and methods, and  will be called at the beginning of the constructor, after the super constructor has been called (either explicitly or implicitly) and before any other subsequent constructor code is called. I've seen it used when a class has multiple constructors and needs the same initialization code called for all constructors. Just as with constructors, you should avoid calling non-final methods in this block. The non-static initializer is the only way to do initialization in an anonymous inner class, as those can't have constructors.                                                     
 For example:

Compare this straightforward one-liner, which places data and assignment together:

private static final Map<String, String> map = Collections.unmodifiableMap(    
new HashMap<String, String>() {
{        
put("foo", "bar"); put("one", "two"); // etc    
}
});

With this mess, which must create a separate object due to final only allowing one assignment:

private static final Map<String, String> map;
static {    
Map<String, String> tempMap = new HashMap<String, String>();    
tempMap.put("foo", "bar");    
tempMap.put("one", "two"); // etc    
map = Collections.unmodifiableMap(tempMap);
}
 

--------------------------------------------------------------------------------------------------------------------------
How to remove elements from a collection while iterating:

Iterator: remove( ):

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). The behaviour of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

Working Example:

while(iterator.hasNext()){
iterator.next();
iterator.remove();
 }

 

Throws:
IllegalStateException: - if the next method has not yet been called, or the remove method has already been called after the last call to the next method
Example for IllegalStateException:

while(iterator.hasNext()){
// next() is not called
iterator.remove();
 }

while(iterator.hasNext()){
iterator.remove();
//next() is called after remove()
iterator.next();
 }

Note:
  1. Enumeration has2 methods: hasMoreElements(), nextElement()
  2. Iterator has 3 methods: hasNext(), next(), remove(). It is an interface
  3. ListIterator: A sub-interface of Iterator, and allows the programmer to traverse the list in either direction, modify the list during iteration
  4. If you want to get iterator for Map, then you can get it by calling on entrySet() of Map
  5. If you try to remove elements using for loop, you will get: java.util.ConcurrentModificationException

Wednesday, January 30, 2013

String, StringBuffer & StringBuilder

Most important interview question right :). Let us have a single line use case for each:

String: If the text is not going to change use a String Class because it is immutable.

StringBuffer: If the text can changes, and will be accessed from multiple threads, use StringBuffer because it is synchronous.

StringBuilder: (Available from Java 5): If the text can change and will only be accessed from a single thead, use StringBuilder as it is immutable and unsynchronized.


 

Monday, December 17, 2012

Use of & in Java

When we use && in conditional statement(if), we know that, if the first condition is false then it won't execute the second condition.

But if we use & instead of && in conditional statement(if), then it will execute the second condition though the first condition is false:

public class TypoMistake {

    public static void main(String[] args) {
       
        boolean isTrue = false;
       
        if(isTrue & isTrue()){
            System.out.println("I am in second for loop");
        }
    }
   
    public static boolean isTrue(){
        System.out.println("I am in isTrue() method");
        return true;
    }

}

Output:
I am in isTrue() method

Monday, September 3, 2012

Reading text file - Java 7

try(FileReader fileReader = new FileReader("src/myfile.txt");
    BufferedReader reader = new BufferedReader(fileReader)){
           
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}

Assumptions:
1. myfile.txt is available in eclipse's src directory.

Monday, August 13, 2012

Split String to equal length substrings in Java

Solution1: Use of Regular Expressions
System.out.println(Arrays.toString(
    "abcdefghij".split("(?<=\\G.{4})")
));

Output1:
[abcd, efgh, ij]

Solution2: Use of simple for Loop
String text = "abcdefghij";
 int size = 4;

        for (int start = 0; start < text.length(); start += size) {
            System.out.println( text.substring(start, Math.min(text.length(), start + size)));
        }

Output2:
abcd
efgh
ij

Solution3: Use of Splitter class(Guava from Google)
for(final String token :
    Splitter.fixedLength(4).split("abcdefghij")){
    System.out.println(token);
}

Monday, July 30, 2012

32 bit JVM or 64 bit JVM

How can I tell if I'm running in 64-bit JVM or 32-bit JVM?

Sun has a Java System property to determine the bitness of the JVM: 32 or 64:

We can access it as follows:
System.getProperty("sun.arch.data.model") 

Way 2:
java -d64 -version
java -d32 -version

Friday, July 27, 2012

Swing Alert box

To pop up Simple alert using Java Swings:

JOptionPane.showMessageDialog(new JFrame(), "Hello World");

Runnable .jar file

To make a runnable jar file, we need to first add the following line in the MANIFEST.MF file:
Main Class: [Package Name].[Class Name]

For Example:
Main Class: com.pramod.MainProgram

To run the jar:
java -jar TeatJar.jar

Tuesday, July 24, 2012

Core Java - Strings

Split a String with . (a dot):
String test_str = "com.pramod.package";
String[] str = test_str.split("\\.");

Friday, July 13, 2012

J2SE 5 Features

  1. Generics
  2. For-each Loop (Enhanced For Loop)
  3. Auto-boxing /unboxing
  4. Enumerations
  5. Variable Arguments
  6. Static Imports
  7. Annotations (Metadata)
  8. Formatted I/O
  9. Concurrency Utilities
  10. Management Utilities
  11. Class Data Sharing

Java 6 Features

  1. Scripting
  2. Web Services
  3. Database (JDBC 4.0, Java DB)
  4. More Desktop APIs
  5. Monitoring & Management
  6. Compiler Access
  7. Pluggable Annotations
  8. Desktop Deployment
  9. Security
  10. Quality, Compatibility, Stability

Java 7 Features

  1. Binary Literals
  2. Underscores in Numeric Literals
  3. String in switch Statements
  4. Diamond operator(<>) (Type Inference for Generic Instance Creation)
  5. Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
  6. The try-with-resources statement
  7. Catching Multiple Exception Types and Re throwing Exceptions with Improved Type Checking