• Streams & Subjects

    Streams & Subjects

    Get detailed description of each and every topic with proper examples including text, images and videos.

  • Latest Technologies

    Latest Technologies

    Know more about the latest and new emerging technologies and boost your knowledge.

  • Programming

    Programming

    Don't learn just codes and syntax, instead learn the best and efficient way of coding.

  • Technologies

    New Technologies

    Get instant and relevant updates of the latest emerging technologies of lots of streams including web, clouds, virtualization, etc.

  • Freewares

    Freewares

    Download free trials and freewares of various fields and check out their efficiency before buying.

  • Multimedia

    Multimedia

    Learn techniques to design amazing and creative multimedia designs and characters including 2D & 3D layout with rendering.

A Beginning Programmer's Guide to Java

A Beginning Programmer's Guide to Java


Dino Programmers Need Not Fear Java

Posted: 28 Nov 2012 08:48 PM PST

While most of this blog focuses on assisting beginning programmers to learn Java as their first computer language, I also try to make it useful to those who are "old school" programmers, like myself, that want to make the transition to the newer language.

I was an accomplished programmer in many procedural and functional languages before I came to any of the Object-Oriented languages. In fact, my favorite language was Modula-2, which worked so well for me doing everything that OO languages were said to do, that I didn't make the transition to OO until about 1994 (a bit late in the game for those who were supposedly active in taking up new languages back then.)

Tools Getting in the Way of the Work
When I came to OO, I had a real hard time learning the whole OO "thing". Much of it looked no different than language structures that enforced normal coding practices used elsewhere. Other parts of it just looked like un-needed restrictions on data access. It was very frustrating.

Part of what slowed my transition to OO had nothing to do with the languages, however. The tools were new, too. That is, I was trying to do things as I was advised to by those more experienced than myself. Rather than using my usual technique of starting out with a text editor and command line compiler and linker, I allowed myself to be talked into going whole hog on IDE interfaces I wasn't familiar with. Once I was in them, I did get some information from them as I worked that helped a bit. But they kept me from really understanding the languages themselves for about a year longer (when nibbling at them part time outside my usual work) than it would have otherwise.

Welcome, Fellow Dinos!
When I started this blog, I strongly considered focusing it on other programmers like myself trying to get comfortable with the move from older languages and programming styles. By the time I did, I was actually pretty comfortable with several OO languages and many development environments and tool chains. But I could still feel the tug of Turbo Pascal when I got frustrated, or plain old vi and make with cc and a system-appropriate linker behind it.

In fact, I still do. There are a fair few nights I unwind by firing up my Ampro Little Board Z-80 system, which runs CP/M 2.2, and having at Turbo Pascal or ASM. Just for relaxation.

It's like embroidery or quilting for aging nerds, I guess.

Java for Dinos
I'm good with being called a dino, so I hope it doesn't put you off if you're an old-timer, too. (Am I really an old timer now? Some folks say so.)

Java is really awfully easy to use at the command line. Create a source file with your favorite text editor.* Open up a command line (no matter what OS you're on), cd to the directory where you saved the file, and compile it with:
javac filename.java

Replace filename with your file's name, of course.
At this stage you need to include the .java file extension. It will produce a new file with the same name but a .class extension is on it now.

Once it completes successfully (and if it doesn't, and old timer should be able to read the error messages and line numbers to fix the code), use the following to run your program:
java filename

Note that even though you're running a .class file, you don't specify the file extension for the java runtime. You'll get an error that makes it look like there's something wrong with your file if you do:
>java Howdy.class  Exception in thread "main" java.lang.NoClassDefFoundError: Howdy/class  Caused by: java.lang.ClassNotFoundException: Howdy.class   at java.net.URLClassLoader$1.run(URLClassLoader.java:202)   at java.security.AccessController.doPrivileged(Native Method)   at java.net.URLClassLoader.findClass(URLClassLoader.java:190)   at java.lang.ClassLoader.loadClass(ClassLoader.java:306)   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)   at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

And, if you go to compile your program and get really, really long lists of errors, don't be discouraged. Remember the old maxim--fix the first error. Chances are most or all of the rest are errors that cascaded from the first one.

Why Bother?
Java will get you a lot of code that you'd have to write yourself otherwise. Now, this isn't unique to Java these days, it's become the norm for many languages. But you won't find yourself creating a socket driver or string handling routines. Plus, you can treat Java as either a procedural or functional language if that suits you. I did for the most part until about five years ago or so. I got a lot of work done with it, even at that.

But, I moved on to using Java "as it was meant to be" over time, because it meant rewriting less code, or less work re-using code. I just took getting there one step at a time. Learning how to do everything I did fluently in Modula-2, or LISP, in Java. (Or one of the various Pascals, or C, etc.) Libraries, general purpose re-usable code, flexible data structures, and so on.

Come In and Look Around
Have a look at my Basic Java Articles, listed in the right column. I strive to post actual working code in my examples, in the form of complete programs. So you don't have to guess about how to fit a snippet into your code.

To do this, I often strip away code that would be good to have, but which might cloud the issue. So I don't guarantee that my examples are good coding practice, but only that they are complete working examples of what I'm talking about. And I warn you in the article when it's not the greatest. Full code can also be downloaded from my Java code repository for this blog (also on the right side of every article here.)

If my articles are of use to you, or you think I can improve things, drop me an email.

Thanks.

*I still do a lot of coding in plain old vi, though I've gotten to like the syntax highlighting in vim as well. If I want an IDE, I usually prefer one of the simpler ones like BlueJ or Greenfoot, though I can bury myself complex ones like Eclipse or NetBeans if I really want to. Occasionally I fire up emacs, though I prefer a stripped version of that, too.




Read more

BlueJ Tutorial

BlueJ Tutorial


Last minute suggestions on guess computer application – theory and practical questions for ISC 2013 students

Posted: 28 Nov 2012 03:37 PM PST


ISC computer practical examination carries 100 marks and in this site students can get the programs and solutions of previous year papers. From those practical papers, one can guess what type of question may come in ISC 2013 computer application examination.

Practical computer application for ISC 2013


If we look back to previous years papers, the findings can be summed up as follows:

In 2010 ISC computer application practical examination, the first program was on number. The amount was entered by user and the amount was displayed in words and the denomination available in descending order was also displayed. Second program on the same year was on kaprekar numbers in a specific range and the third program was completely on string.


In ISC 2011 computer application practical paper, the first program was on displaying number in word like if the entered value is 29, the output will be: TWENTY NINE
Second program was again on string, encryption of message and the third was on displaying total number of days of a specific date from the start of year which was an int type array program.

In 2012 ISC computer application practical paper, the first program was on prime-palindrome integers within a range.The second one was on string, manipulation with words
And the third was on 2-d array finding largest and smallest  numbers with position.

From the above it is clear that programs on string and array ( both 1-d and 2-d) are common in all the previous years. This year students of ISC 2013 can expect programs from the following list in their practical examination.


Program on queue, queue implementation of queue for printing job or like that.

BlueJ program on String array - arranging the words in ascending order

Write a program to accept a date in the string format (dd/mm/yyyy) and accept the name of the day on 1st January of the corresponding year. Find the day for the given date.

BlueJ program on decoding encoded string with removing extra blank spaces and modification on alphabet cases

Program on 2-d array may be set in 2013 Computer application practical of ISC 2013. The program may be of finding maximum value row wise and columkn wise, sorting the elements etc .

Reversing words of a string

Finding unique digit numbers

BlueJ Program on displaying date in specific format

BlueJ program on valid Email id checking

Program to reverse a string. Example: Input:I like computer applications Output:I ekil retupmoc snoitacilppa.

BlueJ program on circular decoding

BlueJ program on re-arranging numbers in an array with positive numbers first

BlueJ program to find the total number of days between two dates

For theoretical paper in ISC 2013 computer application examination


Follow the suggestion and guess of ICSE 2013 and the followings topics:

Inheritance in BlueJ 


What is meant by a user defined data type?

 What is the use of static in the main function?

The basic condition for binary search and compare binary search with linear search technique.

Program on merging two ascending lists

Basic String class Functions in BlueJ

BlueJ programs using String Functions


Also go through suggestions for ICSE 2013.


Last minute suggestions on computer application guess questions for ICSE 2013 students

Posted: 28 Nov 2012 07:20 AM PST


Like every year, this year also this site wishes best of luck to all ICSE 2013 students. Students who are following my site are expected to score better marks in ICSE 2013 Computer examination. In this post, I am trying to point out some guess questions in the forthcoming examination and few suggestions.

Theory part in ICSE 2013 Computer Application


Please go through the following topics and I think this would help you in 2013 ICSE Computer Application paper.

What is Object Oriented Programming

 What is object in Object Oriented Programming

 What is Class in Object Oriented Programming
 

What is Constructor

What is Encapsulation in BlueJ

Name any two library packages of java .

  What is meant by a user defined data type?
 

Give an example of syntax error

  What is the scope of the keyword protected in accessing functions?

 What is a parameterized constructor?

 What is the use of static in the main function?

Arithmetic Assignment Operator in BlueJ

Increment and Decrement Operators in Java

Pre conditions of binary search
 

Show the use of logical operator && with an example.
Explain the term – "pass by reference".

Differentiate between indexOf() and valueOf() functions.

Several functions of String class.

Difference between equals () function and == operator.

Break and Continue in BlueJ

Comparison Among Different Loops

while and do-while

while and for

Syntax of Different Decision Making Statements

Differentiate between isUpperCase() and toUpperCase() function.

Advantages of Exception handling.

What is a "fall through" situation in switch case statement.

Write any two rules for naming varible declaration.
 

Write down the difference between prefix and postfix operators.

Conditional operator.

What is meant by polymorphism? Give an example.

State difference between call-by-value and call-by-reference.

Write any two differences in Implicit Type Casting and  Explicit Type Casting.

What is a function?
 

Can there be objects without having any functions?

Why are functions so important for the description of objects?

What is an abstraction?

Can there be multiple abstractions of a real world entity

How are classes and abstraction linked?

What is an object factory?

Use of static keyword in bluej programs

Use of static in variable

What is static method or function

Function calling techniques-Call be reference and call by value in BlueJ

Use of break statement in BlueJ Programs

Use of Scanner class in BlueJ programs

What is private and public specifier in Java?

Difference between '==' and equals ()'.

Compare switch with else-if ladder.

Define 'substring ()' and 'charAt()' function.

Comparision between break and continue

Use of 'this' keyword.

What do you mean by data encapsulation and polymorphism in Java?

Name the package you need to import  for using Scanner class object.

State the difference between while and do-while loop

State the difference between constructor and function

Explain any two type of access specifiers

What are the preconditions of binary search?

What is the role of void keyword in declaration of a function

What is package, give example.

Explain function overloading with example

What is exit control loop? Give example

What is recursive function, give example

So far as programs are concerned, one program on else if ladder ( either tax calculation, discount calculation or bill calculation) is confirmed. Programs on different numbers like perfect number, prime number etc can be expected. In every year ICSE Computer Application paper, one or two programs are found where the questions are very lengthy but the programs are normally very simple. My advice is to read the question carefully and the solution will be very easy.




Read more

400+ Java Interview Questions and Answers blog

400+ Java Interview Questions and Answers blog


CORS and jQuery with Spring MVC, RESTful Web Service and Maven

Posted: 28 Nov 2012 05:17 AM PST



In the post JSONP and jQuery with Spring MVC, RESTful Web Service and Maven we looked at cross domain example with JSONP. JSONP has a number of limitations like, it supports only GET requests and not PUT, POST, DELETE, etc and it does not also send headers across. CORS stands for Cross Origin Resource Sharing, which allows you to share GET, POST, PUT, and DELETE requests and CORS is supported by the modern browsers.The CORS make use of 2 requests.

Request 1: "OPTIONS" request as part of the handshake to determine if cross domain is allowed by the server.

Request 2: GET, POST, PUT, or DELETE request that performs the actual operation on the server.




This example basically extends the JSONP example with only the changes shown here.


Step 1: The JSP file with jQuery, JavaScript, and ajax code snippets. This code snippet also shows extraction of the request headers and populating back the response.


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  <%@ page language="java" contentType="text/html; charset=UTF-8"      pageEncoding="UTF-8"%>  <!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=UTF-8">        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">       <script type="text/javascript" src="/secure/aes-gui/resources/js/jquery/jquery-1.7.2.js"></script>      <title>Spring MVC - CORS and jQuery Tutorial</title>  </head>  <body>     <h3>Spring MVC - CORS and jQuery Tutorial</h3>    <div style="border: 1px solid #ccc; width: 600px;">   Add Two Numbers:      <input id="inputNumber1" name="inputNumber1" type="text" size="5" > +   <input id="inputNumber2" name="inputNumber2" type="text" size="5">   <input type="submit" value="Add" onclick="add()" />      Sum: <span id="sum"></span>         <input type="submit" value="Show Headers" onclick="displayHeaders()" />        </div>        <script type="text/javascript">     function add() {    var url = 'http://DEV:8080/aes-gui/simple/poc/main/add';        console.log("logging...............");        $.ajax({     type : 'GET',     url : url,     data : {      inputNumber1 : $("#inputNumber1").val(),      inputNumber2 : $("#inputNumber2").val()     },     async : false,     contentType : "application/json",     crossDomain : true,     success : function(response, textStatus, jqXHR) {      console.log("reached here");      // data contains the result      // Assign result to the sum id      $("#sum").replaceWith('<span id="sum">' + response + '</span>');      console.log(response);       },     headers: headerData,           error : function(jqXHR, textStatus, errorThrown) {      console.log(errorThrown);     }    });   };      function displayHeaders() {    var req = new XMLHttpRequest();    req.open('GET', document.location, false);    req.send(null);    var headers = req.getAllResponseHeaders().toLowerCase();    console.log(headers);           var splitHeaders = headers.split(/\r\n|\n|\r/g);    console.log("split headers:\n"  + splitHeaders);    for (var i in splitHeaders){     var currVal = splitHeaders[i];     var entry = currVal.split(":");     var headername = entry[0];     var val = entry [1];     console.log(headername + "=" + val);    }           }      var headerData = {};       $(document).ready(function() {       getHeaders();       console.log("document is ready=" + headerData);    });      function getHeaders() {    var req = new XMLHttpRequest();    req.open('GET', document.location, false);    req.send(null);    var headers = req.getAllResponseHeaders().toLowerCase();       var headersArray = {};        var splitHeaders = headers.split(/\r\n|\n|\r/g);    console.log("split headers:\n"  + splitHeaders);    for (var i in splitHeaders){     var currVal = splitHeaders[i];     var entry = currVal.split(":");     var headername = entry[0];     var val = entry [1];     console.log(headername + "=" + val);     if(!(typeof headername === undefined) ) {      if(headername.toUpperCase() === "SID" || headername.toUpperCase() === "MYCUSTOM" || headername.toUpperCase() === "SMUSER"  ){            headersArray[headername]=val;      }        }         }        /* headersArray["firstName"]="arul" ;    headersArray["lastName"]="kumaran" ; */                   console.log(headersArray);        console.log(JSON.stringify(headersArray));    headerData = headersArray;       }     </script>       </body>  </html>   

Step 2: The server needs to have request filter that intercepts the "OPTIONS" request and add the header information required for the CORS to work. The headers to note are Access-Control-Allow-Origin and Access-Control-Allow-Headers.


package com.myapp.accounting.aes.poc.controller;    import java.io.IOException;  import javax.servlet.FilterChain;  import javax.servlet.ServletException;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import org.springframework.web.filter.OncePerRequestFilter;      public class CorsFilter extends OncePerRequestFilter {     @Override      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)              throws ServletException, IOException {          if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {              // CORS "pre-flight" request              response.addHeader("Access-Control-Allow-Origin", "*");              response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");              response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, sid, mycustom, smuser");              response.addHeader("Access-Control-Max-Age", "1800");//30 min          }          filterChain.doFilter(request, response);      }  }    
Step 3: Define the filter on web.xml file. The key is the last two declarations for the filter.

   <?xml version="1.0" encoding="UTF-8"?>    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">     <!-- Processes application requests for Securities component related requests -->   <servlet>    <servlet-name>mvc-dispatcher</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup>   </servlet>     <servlet-mapping>    <servlet-name>mvc-dispatcher</servlet-name>    <url-pattern>/simple/*</url-pattern>   </servlet-mapping>     <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>   </context-param>     <!-- Creates the Spring Container shared by all Servlets and Filters -->   <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   </listener>     <filter>    <filter-name>cors</filter-name>    <filter-class>com.myapp.accounting.aes.poc.controller.CorsFilter</filter-class>   </filter>     <filter-mapping>    <filter-name>cors</filter-name>    <url-pattern>/simple/*</url-pattern>   </filter-mapping>    </web-app>    

The filter will intercept the cross domain OPTIONS request add the relevant headers to allow cross domain.


Step 4: The controller that is actually serving the subsequent RESTful GET, POST, PUT or DELETE requests need to send the relevant headers back. So, in your controller you need to populate the relevant headers as well.


     package com.myapp.accounting.aes.poc.controller;    import java.util.Enumeration;    import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;    import org.springframework.http.HttpHeaders;  import org.springframework.http.HttpStatus;  import org.springframework.http.ResponseEntity;  import org.springframework.stereotype.Controller;  import org.springframework.ui.Model;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RequestMethod;  import org.springframework.web.bind.annotation.RequestParam;    @Controller  @RequestMapping("/poc/main")  public class POCController {     @RequestMapping(value = "/sum", method = RequestMethod.GET)   public String getNonAjaxPage(HttpServletRequest request, HttpServletResponse response) {    Enumeration headerNames = request.getHeaderNames();    while(headerNames.hasMoreElements()){     String nextElement = (String)headerNames.nextElement();     System.out.println(nextElement + "=" + request.getHeaders(nextElement));     response.addHeader(nextElement, request.getHeader(nextElement));    }        //adding som custom headers    response.addHeader("SID", "I573558");    response.addHeader("MYCUSTOM", "CUSTOM");        return "poc-page/ajax-sum";   }      @RequestMapping(value = "/add", method = RequestMethod.GET)   public ResponseEntity<String> add(     @RequestParam(value = "inputNumber1", required = true) Integer inputNumber1,     @RequestParam(value = "inputNumber2", required = true) Integer inputNumber2,     Model model, HttpServletRequest request) {      // Delegate to service to do the actual adding    Integer sum = inputNumber1 + inputNumber2;      String result = null;      // @ResponseBody will automatically convert the returned value into JSON    // format. you must have Jackson in your classpath              result =  sum.toString();            HttpHeaders responseHeaders = new HttpHeaders();        Enumeration headerNames = request.getHeaderNames();    while(headerNames.hasMoreElements()){     String nextElement = (String)headerNames.nextElement();     System.out.println(nextElement + "=" + request.getHeaders(nextElement));     responseHeaders.set(nextElement, request.getHeader(nextElement));    }            //populating the header required for CORS    responseHeaders.set("Access-Control-Allow-Origin", "*");             return new ResponseEntity<String>(result, responseHeaders, HttpStatus.OK);   }  }      
That's all to it. The rest will remain same as the JSONP tutorial.




Read more