How Really Java is Platform Independent

Probably the first thing that is written anywhere about java is that it is a platform independent language. Have you ever wondered that what is meant by platform independent? How java is platform independent? Why other programming languages lack this portability? The purpose of this article is to understand you about all these terminologies.

Before going into detail, first you have to understand that what is a platform?

What Is A Platform? 

A platform consists of computer hardware and Operating system. For example, a PC with Windows 8.

Platform dependent means the program can be executed only on a specific platform. Many programs like Skype can be used on multiple operating systems like Windows or OS X. but notice that this software has different versions for different operating systems, which means that Skype is not actually platform independent. Basically the programs written in dependent languages require some code changes to run on other platforms. C++ is an example of platform dependent programming language.

Platform independent means the program that we have developed can run on any platform. The code remains the same irrespective of the platform involved. Java is an example of platform independent programming language. One Program written in Java can run on Windows or OS X without any modification.


How Java Is Platform Independent:


The reason why java is platform independent is that it is a structured differently from other programming languages. In fact, Java is both compiler and interpreter based language. In other programming languages like C/C++, the source code you write must be compiled in machine code to execute because computers can only execute machine code. The compiler, which compiles the code, uses the functions of the current operating system to compile the source code. This compiled program just runs on that operating system as its code was translated interacting the functions of specific operating system. So, the program becomes platform dependent.

On the other hand, the java compiler compiles the source code and produces an independent intermediate code called byte code instead of direct machine code. This code is platform independent because java compiler doesn’t interact with the local platform while generating byte code. In fact, this code is represented in hexa-decimal format which is same for every platform. You can say that byte code generated on Windows is same as the byte code generated on Linux for the same java code.


Now this code must be converted into machine code to be executed by a computer, here JVM comes. JVM stands for JAVA Virtual Machine and it is available as a part of JDK & JRE (described later) for different operating systems. The JVM translates the byte code into machine code which can be executed by a computer. This JVM works like a virtual machine on which platform independent byte code runs and this machine produces a platform dependent machine code. No matter, what physical platform you are using, the part where JVM interprets byte code is guaranteed to work in the same way. Since all the JVMs work exactly the same, the same code works exactly the same way without recompiling. So the same code works on all operating systems without modification.

How Java Is Platform Independent, when it requires JVM:

In true sense, Java is NOT PLATFORM INDEPENDENT programming language as it requires JVM to run upon. But it works like a platform independent language with pre-installed JRE/JDK on the computer.

JVM comes as a part of JDK and JRE. JDK stands for Java Development Kit which is used to write, compile, debug and execute Java code. While JRE stands for Java Runtime Environment which is required to run java programs. So, every computer must be preloaded with JRE to run any java application.

Mostly computer manufacturers sell their computers with pre-installed JRE. Now, these computers are familiar with programs written in Java language. So, they run/execute the program without demanding a single file.  But, if computer manufacturers have not added JRE in their systems then JRE should be installed manually.

But, wait a minute, think that you want to run a program written in C/C++ (platform dependent code) on another platform then what you would do? Surely you will make some changes in the core code of program. This could be a long and complicated process and you also should have knowledge of the construction of target platform. But, the java program can run on any platform without modifying the code. Just, JVM is required to run the code on any platform exists. Your byte code is same for every platform and JVM converts it into machine code according to local platform. This machine code is then executed by computer.

About Author:
Kamal Choudhary is a tech geek who writes about c++ programming tutorials on C++ Beginner. He is a student of computer science in University of Gujrat, pakistan. He loves to write about computer programming. You can find his full bio here. Follow him on twitter @ikamalchoudhary

How To Make a Age Calculator in Java

This is a age calculator made in java, it's a console application by the way :)

source :

 import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.InputMismatchException;

public class age_calculator {

    public static void main(String[] args) {
        int day = 0;
        int month = 0;
        int year = 0;
        Scanner scan = new Scanner(System.in);
  try{
         System.out.print("Day: ");
         day = scan.nextInt();
         System.out.print("Month: ");
         month = scan.nextInt();
         System.out.print("Year: ");
         year = scan.nextInt();
  }
  catch(InputMismatchException e){
   System.out.println("Error: You entered an invalid number");
   System.exit(1);
  }
        System.out.println("\nYou are " + getAge(day,month,year) + " years old");
    }

    public static int getAge(int day, int month, int year){
  final int ERROR = -1;

        //initialize GregorianCalendar with current date
        GregorianCalendar cal = new GregorianCalendar();
        //constant holds current day
        final int CDAY = cal.get(GregorianCalendar.DAY_OF_MONTH);
        //constant hold current month
        final int CMONTH = cal.get(GregorianCalendar.MONTH) + 1;
        //constant to hold current year
        final int CYEAR = cal.get(GregorianCalendar.YEAR);
        //check if current day of the month is greater then birth day
        if (month == CMONTH){
            if(CDAY >= day)
                return CYEAR - year;
   if(CDAY < day)
    return CYEAR - year - 1;
        }
        //check if birth month is less then current month
        else if(month < CMONTH)
            return CYEAR - year;
        //subtract 1 from the age because  the current day in the month is less then birth date
  else
         return CYEAR - year - 1;
  return ERROR;
    }

} 

screenshot :
 How To Make a Age Calculator in Java
 Hope it helped you :)

Java Port Scanner Full Source Code

Java Port Scanner Full Source Code


Here is the full source code :





/*+---------------------------------Adeel Mahmood---------------------------------+*\

/*+---------------------------------Port Scanner----------------------------------+*\

/*=-------------------------adeelmahmood1982@ukonline.co.uk------------------------+*\

/************************************************************************************/





import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class PortScanner extends Frame{



Socket s;
int startPort,endPort;
Label l1;
TextField hostName,fromPort,toPort;
TextArea log;
Label host,from,to,label;
Button scan,reset;
int fp,tp;
String h;
static boolean close=false;
Dialog d;


public PortScanner(){

Frame f=new Frame("Port Scanner");

f.setVisible(true);
f.setLayout(new GridLayout(5,1));

l1=new Label("Port Scanner version 1.0",Label.CENTER);
l1.setForeground(Color.blue);
l1.setFont(new Font("TimesRoman",Font.BOLD,20));
f.add(l1);

Panel p1=new Panel(new GridLayout(3,3));
host=new Label("Host Name:");
host.setForeground(Color.blue);
p1.add(host);
hostName=new TextField(15);
p1.add(hostName);
from=new Label("From Port:");
from.setForeground(Color.blue);
p1.add(from);
fromPort=new TextField(15);
p1.add(fromPort);
to=new Label("To Port:");
to.setForeground(Color.blue);
p1.add(to);
toPort=new TextField(15);
p1.add(toPort);

f.add(p1);

Panel p2=new Panel();
scan=new Button("Scan Now");
scan.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent r){
if(hostName.getText().equals("")){log.setText("Please complete all the required fields");
return;
}
 else if (fromPort.getText().equals("")){log.setText("Please complete all the required fields");
return;}
  else if(toPort.getText().equals("")){log.setText("Please complete all the required fields");
return;}
   
close=false;
Thread run1=new Thread(){
public void run(){

scan.setEnabled(false);
reset.setLabel("Stop");
log.setText("");
log.repaint();

h=hostName.getText();
fp=Integer.parseInt(fromPort.getText());
tp=Integer.parseInt(toPort.getText());

for(int i=fp;i<=tp;i++){
label.setText("Port "+i+" is being tested");
 if(close)
 break;
 try{
 s=new Socket(h,i);
 log.append("Port "+i+" is open."+"\n");
 log.repaint();
 s.close();
 }
 catch(Exception er){continue;}
 
}
scan.setEnabled(true);
reset.setLabel("Reset");
label.setText("Press Scan to start.");
}
};
run1.start();
}
});



reset=new Button("Reset");
reset.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent t){
Thread run2=new Thread(){
public void run(){
close=true;
hostName.setText("");
fromPort.setText("");
toPort.setText("");
}
};
run2.start();
}
});





Label empty=new Label();
p2.add(scan);
p2.add(empty);
p2.add(reset);
f.add(p2);

log=new TextArea();
f.add(log);

label=new Label("Press Scan to start.");
label.setForeground(Color.blue);
f.add(label);

f.setSize(320,460);
//f.show(true);
f.repaint();
f.setResizable(false);

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(1);
}
});


}

public static void main(String args[]){

new PortScanner();
}



}// end of class

Enjoy, please comment if you have any problems.

How To Make a Line Break/New Line in Java

How To Make a Line Break/New Line in Java
Line Break or New Line : I hope you understand what it is, in HTML you use <br> tag to make a new line so in Java if you want to make a new line it's not that hard but it has several methods depends on the platform.

Coming to the point, most of the java beginners think this is the one and only way to make a new line : System.out.println("\n"); but It's not true.. let me tell you something you might think that whatever you program using java will work on other java supported platforms, YES! they will work on other platforms but there are few things that has to be changed in order to get the functions work.. for example this tutorial; this line of code : System.out.println("\n"); would make a new line only on Windows. As I said before there are few things that are different from platform to platforms.

If you want to make a new line on Mac you must use this : System.out.println("\r"); and for Linux you have to use this : System.out.println("\r\n");. So I came up with something that works on all the platforms, It's pretty simple and works perfectly.

First you need to make a public string and set the value to make a new line(You can also just make normal string and set the value)
Add this line of code before your main event
public static String breakline = System.getProperty("line.separator");

Whenever you need to make a new line just use this line of code 
You can add this wherever you want to
System.out.println(breakline);

Please comment if you have any doubts..!

How To Get Response Headers From a HTTP Request in Java

With this Java program you can get the the response headers from a HTTP request. You may have seen HTTP headers in Google Chrome/Mozilla Firefox network feature in inspect element (it just automatically captures HTTP).

All you have to do is run the program from command-line or on eclipse (or any IDE you want), after executing the program you will be asked to enter an URL to get the response headers from HTTP request (Note : make sure you don't enter URL's without 'http://'). Within seconds you will get the HTTP request response headers one after the next line.

This program has 7 namespaces, of course you need them in order to compile/execute the program
import java.util.Scanner;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

and we are using a public string that helps to make a line break
public static String BR = System.getProperty("line.separator");

Okay let me put all the parts together, it uses Scanner(that to get the users input), Map, List, Set, Iterator, a while loop, String Builder and finally it prints.

Program Source Code
import java.util.Scanner;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/* 
Author : Mohamed Shimran
Description : Getting Response Headers From a HTTP Request
Blog : http://ultimateprogrammingtutorials.info
Facebook : http://fb.me/54j33dh4
Twitter : http://twitter.com/54j33dh4
 */
 
public class httpRequest {
public static String BR = System.getProperty("line.separator");
public static void main(String[] args) throws Exception {

  String Link;
     Scanner in = new Scanner(System. in );
     System.out.println("Enter Link To Get Response Headers From HTTP Request :");
     Link = in .nextLine();
   
System.out.println(BR);

 URL url = new URL(Link);
 URLConnection conn = url.openConnection();
 
 Map> HF = conn.getHeaderFields();
 Set HFS = HF.keySet();
 Iterator HFI = HFS.iterator();
 
 while (HFI.hasNext()) {

      String HFK = HFI.next();
      List HFV = HF.get(HFK);

      StringBuilder strbld = new StringBuilder();
      for (String value : HFV) {
   strbld.append(value);
   strbld.append("");
   }
      System.out.println(HFK + "=" + strbld.toString());
   }
   }
}

Process
javac httpRequest.java

java httpRequest
Enter Link To Get Response Headers From HTTP Request :
http://www.ultimateprogrammingtutorials.info

null=HTTP/1.1 200 OK
ETag="5064ad83-05c5-4cef-bbba-a3030b0727da"
Transfer-Encoding=chunked
Date=Wed, 15 Jan 2014 14:12:06 GMT
X-XSS-Protection=1; mode=block
Expires=Wed, 15 Jan 2014 14:12:06 GMT
Alternate-Protocol=80:quic,80:quic
Last-Modified=Wed, 15 Jan 2014 14:10:59 GMT
Content-Type=text/html; charset=UTF-8
Server=GSE
X-Content-Type-Options=nosniff
Cache-Control=private, max-age=0



How To Get Response Headers From a HTTP Request in Java

Final Words
What can I say? It's just another simple java program by me(of course got help from many resources). I hope you really like it or found it useful, share it if it deserves and PEACE!.

How To Submit Software, Mobile App and Game On Softpedia

Softpedia Blue Background
Softpedia is a site where you can find computer programs and technology based articles. It's owned by SoftNews NET SRL, a Romanian company. It was launched in 2001. My programs have been reviewed by the Softpedia editors thrice. I submit my programs whenever they are ready to be released.

I have been asked a few times about this(how to submit..). It's pretty easy to submit your programs to Softpedia all you have to do is fill the form fields and submit.

They have different pages to submit for different platforms such as Windows, Linux, Mac etc.

Submit Windows Softpedia

Submit Games and Tools

Submit Mac OS Software

Submit Linux Software

Submit Mobile App

NOTE : you can submit your java programs in any section except Mobile.

Make sure you go to the right page, if you have a PAD file for your software already just fill the PAD form fields and submit if not fill the regular submission forms and submit. Don't forget to give your regular email address they'll send you an email when your program has been published.

What is JDBC Driver and JDBC Architecture

JDBC stands for Java Database Connectivity. JDBC drivers helps you to open database connection and to interact with it by executing SQL queries then receiving the results with Java. The Java.sql namespace that ships JDK has various classes with their behaviors defined and their actual implementation are done in the third-party drivers.

How To Make Message Boxes In Java

Message boxes are used to display alerts and information messages to the user. It’s very easy to make Message Boxes in .NET languages, however in Java programming language it’s not very easy like in vb/c#. In Java we can use JOptionPane to display messages.

How To Keep JFrame Always On Top

Always On Top : It’s something that keeps the window on top, you might have seen in some programs they have a menu strip item called Always On Top when you enable it, it will keep the window on top most. You might have seen in Visual Basic or Visual C-Sharp they have a property for that in Form properties so you don’t need to write codes for that but in Java you all know that they neither have a official IDE nor a well advanced 3rd party IDE such as Visual Studio.

Simple TinyURL API in Java

I have been off for sometime for some issues anyway today we are going to see how to use TinyURL API in Java programming language.Well, to be honest theres nothing so serious I have imported Scanner to input, of course the GET request and some more to handle the exceptions and so. I'd like to say that I like console based(CLI) applications more than GUI so I don't bother about forms and others.

How Java Works

In Java programming language, all source code is written first in plain text files ending with the .java extension. Those source files are then compiled into .class files by the java compiler. A .class file doesn't contain code that is native to your processor, it instead contains bytecodes. Bytecode is the machine language of Java Virtual Machine(Java VM). The Java launcher tool then runs your program with an instance of the Java Virtual Machine.

Snippet : Using Regular Expressions in Java

This snippet helps you to use Regular Expression(Regex) in Java.

Snippet : Get ASCII Value For Every Characters

This snippet helps you to get the ASCII value for every characters.

How To Execute Shell Commands and Print Results in Java

Java Command Shell,bash script -eq, bash script -ne, best way to learn java, execute shell commands, execute shell commands java, get runtime, host runtime, java, java learning, oracle sql plsql, print results, tutorial,
There are many ways to execute shell commands and print results in java I guess, the famous and the most used way is Runtime.getRuntime().exec you can find a good explanation for that from here. Coming to the point i am using the same way but little different! I use BufferedReader,InputStreamReader for simplicity and I can't make it much advanced. On the main event I have created a String where you put your command with the second event it executes the command and prints the result before I start I would like to give some credits to luismcosta.

Syntax Highlighter For Blogger

Syntax
I have been using Alex Gorbatchev Syntax Highlighter for a long while now . someone requested me to write an article about using this syntax highlighter in blogger so here i go .

Select a theme for the syntax highlighter , those links have previews of the theme.
Now add these codes under your head in your html .



After adding those codes now it's time to set your theme to the syntax highlighter , in the third line of code that i gave before . this parameter is what i meant

code
now after styles/ add the theme style , you can see the theme style right after the theme preview link . for example i have selected shThemeRDark.css then my parameter would look like this

line


Now you have successfully added the syntax highlighter now save your template and now we will test the syntax highlighter . you cannot just add the code and let it define the language , you should define the language in the tag . you can see what language we can highlight from here  . coming to the point i will show you how to syntax highlight a java hello world program .

go to the HTML tab in your post and find where you want the syntax highlighter to be and here we go
replace ____ with your language name and replace codes with your codes and that's how it works . here is a sample of the syntax highlighter.
public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World");
    }

}
Thanks For Reading , Have A Great day .

How To Capture Entire Screen In Java


capture jn
Another quick tutorial on capturing your entire screen with java actually sometimes java makes me mad because sometimes i have to import loads of namespaces than c# or vb.net anyways , as usual to do something in system we import IO thingy yes we are using it here .

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;

class Snap
{
 public static void main(String args[]) throws Exception
 {
     Robot awt_robot = new Robot();
  BufferedImage Entire_Screen = awt_robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
  ImageIO.write(Entire_Screen, "PNG", new File("Entire_Screen.png"));
 }
}

How To List Down Countries In Java

java countries
Java is something what really impressed me than other programming languages anyways today we'll see how to list down all the countries and their country code . I don't know whether you know theres a small library called Locale in java.util namspace so that's what i am using here to do the thing .

import java.util.*;
 /* Author : Mohamed Shimran
    Blog : http://ultimateprogrammingtutorials.blogspot.com
 */
class Countries {
    public static void main(String args[]) {
    String[] cntry = Locale.getISOCountries();
 for (String countryCode : cntry) {
  Locale obj = new Locale("", countryCode);
  System.out.println("Country Code = " + obj.getCountry() 
   + ", Country Name = " + obj.getDisplayCountry());
  }
    }
}
NOTE: i was using public class but i had to remove it because my class thingy goes mad still it works actually public class is not needed.

Infographic : Brief History About Programming

Here is a Brief History About Programming in a form an infographic which i found while surfing over the web pages :)

brief  Programming



Click here to view the image

How To Set Up Java In Windows

I saw many people having problems in setting up the java compiler so I just thought of doing a tutorial on this so on here i am .. , first of all download the latest version of java by the way remember to download it from oracle website and not from other websites also you should download JDK(Java Developer(s) Kit) , then install it as usual. After installing go for a restart then after the next switch in go ahead and right click My Computer and select Advanced System Properties .

How To Make Beeb Sound On Each Word In Java

How To Make Beeb Sound On Each Word In Java
hello guys , so you all know what is a beeb sound so on in vb.net or c-sharp it's veru easy to make beeb sound.

if you want to make beeb sound in vb.net here is the code
 Microsoft.VisualBasic.Interaction.Beep()

if you want to make beeb sound in c# here is the code

using Microsoft.VisualBasic;
using System.Media;

SystemSounds.Beep.Play();

ok now let's turn to java side

here is the codes that i wrote to do this , i am using arrays and a for loop and a thread.

actually i had to write this for a homework.