blogspot visit counter

Saturday 9 March 2013

Introduction to Java programming

Introduction to Java programming

Introduction to Java programming

Categories-:
Run Java Porgram Using Command Prompt  
 How i can Check Java is Installed in my Computer  
 java_home environment variable
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding on Java.
ples for standard programming tasks.

1. Introduction to Java

1.1. History

Java is a programming language created by James Gosling from Sun Microsystems in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.
Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
From the Java programming language the Java platform evolved. The Java platform allows that the program code is written in other languages than the Java programming language and still runs on the Java virtual machine.

1.2. Java Virtual machine

The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.
The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into so-called bytecode. The Java virtual machine interprets this bytecode and executes the Java program.

1.3. Object Oriented Programming

Since Java is an object oriented programming language it has following features:
  • Reusability of Code
  • Emphasis on data rather than procedure
  • Data is hidden and cannot be accessed by external functions
  • Objects can communicate with each other through functions
  • New data and functions can be easily addedJava has powerful features. The following are some of them:-

    Simple
    Reusable
    Portable (Platform Independent)
    Distributed
    Robust
    Secure
    High Performance
    Dynamic
    Threaded
    Interpreted
Object Oriented Programming is a method of implementation in which programs are organized as cooperative collection of objects, each of which represents an instance of a class, and whose classes are all members of a hierarchy of classes united via inheritance relationships.
OOP Concepts
Four principles of Object Oriented Programming are
Abstraction
Encapsulation
Inheritance
Polymorphism
Abstraction
Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.
Encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation.
Encapsulation
* Hides the implementation details of a class.
* Forces the user to use an interface to access data
* Makes the code more maintainable.
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
Polymorphism
Polymorphism is the existence of the classes or methods in different forms or single name denoting different
implementations.

Java is Distributed

With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objects across net via URLs.


Java is Multithreaded

One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrently within the same program A single Java program can have many different threads executing independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU time.

Java is Secure

Java was designed to allow secure execution of code across network. To make Java secure many of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory.

Garbage collection

Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is done automatically with garbage collector.

Java Applications

Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant enterprise-enabled programming language suitable for developing significant and critical applications. Today, It is used for many types of applications including Web based applications, Financial applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and many more.

1.4. Java Runtime Environment vs. Java Development Kit

Java comes in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK).
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.

Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the central role in this concept. The JVM is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system. When the source code (.java files) is compiled, it is translated into byte codes and then placed into (.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM. A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler. The JVM must be implemented on a particular platform before compiled programs can run on that platform.

1.5. Characteristics of Java

The target of Java is to write a program once and then run this program on multiple operating systems.
Java has the following properties:
  • Platform independent: Java programs use the Java virtual machine as abstraction and do not access the operating system directly. This makes Java programs highly portable. A Java program which is standard complaint and follows certain rules can run unmodified on all supported platforms, e.g. Windows or Linux.
  • Object-orientated programming language: Except the primitive data types, all elements in Java are objects.
  • Strongly-typed programming language: Java is strongly-typed, e.g. the types of the used variables must be pre-defined and conversion to other objects is relatively strict, e.g. must be done in most cases by the programmer.
  • Interpreted and compiled language: Java source code is transferred into the bytecode format which does not depend on the target platform. These bytecode instructions will be interpreted by the Java Virtual machine (JVM). The JVM contains a so called Hotspot-Compiler which translates performance critical bytecode instructions into native code instructions.
  • Automatic memory management: Java manages the memory allocation and de-allocation for creating new objects. The program does not have direct access to the memory. The so-called garbage collector deletes automatically objects to which no active pointer exists.

The Java syntax is similar to C++. Java is case sensitive, e.g. the variables myValue and myvalue will be treated as different variables.

1.6. Development Process with Java

The programmer writes Java source code in a text editor which supports plain text. Normally the programmer uses an Integrated Development Environment (IDE) for programming. An IDE supports the programmer in the task of writing code, e.g. it provides auto-formating of the source code, highlighting of the important keywords, etc.
At some point the programmer (or the IDE) calls the Java compiler (javac). The Java compiler creates the bytecode instructions. . These instructions are stored in .class files and can be executed by the Java Virtual Machine.

1.7. Classpath

The classpath defines where the Java compiler and Java runtime look for .class files to load. This instructions can be used in the Java program.
For example if you want to use an external Java library you have to add this library to your classpath to use it in your program.

2. Installation of Java

Java might already be installed on your machine. You can test this by opening a console (if you are using Windows: Win+R, enter cmd and press Enter) and by typing in the following command:

java -version 
If Java is correctly installed, you should see some information about your Java installation. If the command line returns the information that the program could not be found, you have to install Java. The central website for installing Java is the following URL:

http://java.com 
If you have problems installing Java on your system, a Google search for How to install JDK on YOUR_OS should result in helpful links. Replace YOUR_OS with your operating system, e.g. Windows, Ubuntu, Mac OS X, etc.

3. Your first Java program

3.1. Write source code

The following Java program is developed under Microsoft Windows. The process on other operating system should be similar but is not covered in this description.
Select a new directory which will contain your Java code. I will use the c:\temp\java which will be called javadir in the following description.
Open a text editor which supports plain text, e.g. Notepad under Windows and write the following source code. You can start Notepad via StartRunNotepad and by pressing enter.

// A small Java program 
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}




Save the source code in your javadir directory with the HelloWorld.java filename. The name of a Java source file must always equals the class name (within the source code) and end with the .java extension. In this example the filename must be HelloWorld.java because the class is called HelloWorld.

3.2. Compile and run your Java program

Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to the javadir directory with the command cd javadir, for example in my case cd c:\temp\java. Use the command dir to see that the source file is in the directory.

javac HelloWorld.java 
Check the content of the directory with the command "dir". The directory contains now a file "HelloWorld.class". If you see this file you have successfully compiled your first Java source code into bytecode.
By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d compiler flag.
Run -> cmd. Switch to the directory jardir.
To run your program type in the command line:

java HelloWorld 
The system should write "Hello World" on the command line.



3.3. Using the classpath

You can use the classpath to run the program from another place in your directory.
Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to any directory you want. Type:

java HelloWorld 
If you are not in the directory in which the compiled class is stored then the system should result an error message Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass
To use the class type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.

java -classpath "mydirectory" HelloWorld 

4. Integrated Development Environment

The previous chapter explained how to create and compile a Java program on the command line. A Java Integrated Development Environment (IDE) provides lots of ease of use functionality for creating java programs. There are other very powerful IDE's available, for example the Eclipse IDE. .
For an introduction on how to use the Eclipse IDE please see Eclipse IDE Tutorial.
In the following I will say "Create a Java project SomeName". This will refer to creating an Eclipse Java project. If you are using a different IDE please follow the required steps in this IDE.

5. Your first graphical user interface application (GUI)

Using Eclipse create a new Java project "JavaIntroductionUI".
Create the following class MyFirstUI.java in package ui.

package ui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MyFirstUI extends JFrame {

private JCheckBox checkbox;
private JTextField firstName;
private JTextField lastName;

public MyFirstUI() {

// Lets make it look nice
// This you can ignore
//delete if you do not like it
// try {
// for (LookAndFeelInfo info : 
UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }

setTitle("My First UI");

// We create a panel which will 
//hold the UI components
JPanel pane = new JPanel(new BorderLayout());
// We always have two UI elements 
(columns) and we have three rows
int numberOfRows = 3;
int numberOfColumns = 2;
pane.setLayout(new GridLayout
(numberOfRows, numberOfColumns));

// create and attach buttons
// create a label and add it to the main window
JLabel firstNamelabel = new JLabel
(" Firstname: ");
pane.add(firstNamelabel);
firstName = new JTextField();
pane.add(firstName);

JLabel lastNamelabel = new JLabel(" Lastname: ");
pane.add(lastNamelabel);
lastName = new JTextField();
pane.add(lastName);

JButton sayHello = new JButton("Say something");
pane.add(sayHello);

checkbox = new JCheckBox("Nice");
pane.add(checkbox);

// Add the pane to the main window
getContentPane().add(pane);

// Pack will make the size of 
//window fitting to the compoents
//You could also use for example setSize(300, 400);
pack();

// Set a tooltip for the button
sayHello
.setToolTipText("This button will say something 
really nice of something bad");
// sayHello need to do something 
sayHello.addActionListener(new MyActionListener());
}
private class MyActionListener implements 
 ActionListener {
 public void actionPerformed(ActionEvent e) {
if (!checkbox.isSelected()) {
JOptionPane.showMessageDialog(null,"I do not like 
you,"
+firstName.getText() + " " + lastName.getText() +
 "!");
} else {
JOptionPane.showMessageDialog(null, "How are 
you, " 
+firstName.getText() + " " + lastName.getText() 
+ "?");
}
}

}
}

Create also the following class MainTester.java in package test and start this class.

package test;

import ui.MyFirstUI;

public class MainTester {
public static void main(String[] args) {
MyFirstUI view = new MyFirstUI();
view.setVisible(true);
}
}

You should see the following. A mesage dialog should be seen if you press the button.




 

6. Statements

The following describes certain aspects of the software.

6.1. Boolean Operations

Use == to compare two primitives or to see if two references refers to the same object. Use the equals() method to see if two different objects are equal.
&& and || are both Short Circuit Methods which means that they terminate once the result of an evaluation is already clear. Example (true || ....) is always true while (false && ...) always false is. Usage:
(var !=null && var.method1()..) ensures that var is not null before doing the real check.


Table 1. Boolean
Operations Description
== Is equal, in case of objects the system checks if the reference variable point to the same object, is will not compare the content of the objects!
&& And
!= is not equal, similar to the "=="
a.equals(b) Checks if string a equals b
a.equalsIgnoreCase(b) Checks if string a equals b while ignoring lower cases
If (value ? false : true) {} Return true if value is not true. Negotiation


6.2. Switch Statement

The switch statement can be used to handle several alternatives if they are based on the same constant value.

switch (expression) { 
case constant1:
command;
break; // Will prevent that the other cases
//or also executed
case constant2:
command;
break;
...
default:
}

Example:

switch (cat.getLevel()) {
case 0:
return true;
case 1:
if (cat.getLevel() == 1) {
if (cat.getName().equalsIgnoreCase(req.
getCategory())) {
return true;
}
}
case 2:
if (cat.getName().equalsIgnoreCase(req.
getSubCategory())) {
return true;
}
}

7. Working with Strings

The following lists the most common string operations.


Table 2. 
Command Description
text1.equals("Testing"); return true if text1 is equal to "Testing". The test
 is case sensitive.
text1.equalsIgnoreCase("Testing"); return true if text1 is equal to "Testing". The
test is not case sensitive. For example it would
also be true for "testing"
StringBuffer str1 = new StringBuffer(); Define a new String with a variable length.
str.charat(1); Return the character at position 1.
(Strings starting with 0)
str.substring(1); Removes the first characters.
str.substring(1, 5); Gets the substring from the second to
the fifths character.
str.indexOf(String) Find / Search for String Returns the index of
the first occurrence of the specified string.
str.lastIndexOf(String) Returns the index of the last occurrence of
 the specified string. StringBuffer does not
support this method. Hence first convert
the StringBuffer to String via method toString.
str.endsWith(String) Returns true if str ends with String
str.startsWith(String) Returns true if str starts with String
str.trim() Removes spaces
str.replace(str1,str2) Replaces all occurrences of str1 by str2
str.concat(str1); Concatenates str1 at the end of str.
str.toLowerCase() str.toUpperCase() Converts string to lower- or uppercase
str1 + str2 Concatenate str1 and str2
String[] zeug = myString.split("-"); String[] zeug = myString.split("\\."); Spits myString at / into Strings. Attention:
 the split string is a regular expression,
 so if you using special characters which
 have a meaning in regular expressions
 you need to quote them. In the second
 example the . is used and must be
 quoted by two backslashes.


8. Type Conversion

If you use variables of different types Java requires for certain types an explicit conversion. The following gives examples for this conversion.

8.1. Conversion to String

Use the following to convert from other types to Strings

// Convert from int to String
String s1 = String.valueOf (10);//"10" String s2 =
// Convert from double to String
String.valueOf (Math.PI); // "3.141592653589793"
// Convert from boolean to String
String s3 = String.valueOf (1 < 2); // "true"
// Convert from date to String
String s4 = String.valueOf (new Date()); 
// "Tue Jun 03 14:40:38 CEST 2003" 

8.2. Conversion from String to Number


// Conversion from String to int
int i = Integer.parseInt(String);
// Conversion from float to int
float f = Float.parseFloat(String);
// Conversion from double to int
double d = Double.parseDouble(String);

The conversion from string to number is independent from the Locale settings, e.g. it is always using the English notification for number. In this notification a correct number format is "8.20". The German number "8,20" would result in an error.
To convert from a German number you have to use the NumberFormat class. The challenges is that if the value is for example 98.00 then the NumberFormat class would create a Long which cannot be casted to Double. Hence the following complex conversion class.

private Double convertStringToDouble(String s) {

Locale l = new Locale("de", "DE");
Locale.setDefault(l);
NumberFormat nf = NumberFormat.getInstance();
Double result = 0.0;
try {
if(Class.forName("java.lang.Long").
isInstance(nf.parse(s))) {
result = Double.parseDouble(String.
valueOf(nf.parse(s)));
} else {
result = (Double) nf.parse(new String(s));
}
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
return result;
}

8.3. Double to int

int i = (int) double;

8.4. SQL Date conversions

Use the following to convert a Date to a SQL date

package test;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ConvertDateToSQLDate {

private void convertDateToSQL(){
SimpleDateFormat template =
new SimpleDateFormat("yyyy-MM-dd");
java.util.Date enddate =
new java.util.Date("10/31/99");
java.sql.Date sqlDate = 
java.sql.Date.valueOf(template.format(enddate)); 

}
public static void main(String[] args) {
ConvertDateToSQLDate date = new 
ConvertDateToSQLDate();
date.convertDateToSQL();
}

}

9. Cheat Sheets

The following can be used as a reference for certain task which you have to do.

9.1. Working with classes

While programming Java you have to create several classes, methods, instance variables.
The following uses the package test.


Table 3. 
What to do How to do it
Create a new class called MyNewClass.
package test;

public class MyNewClass {

}

Create a new attribute (instance variable) "var1" in MyNewClass with type String
package test;

public class MyNewClass {
private String var1;
}

Create a Constructor for "MyNewClass which has a String parameter and assigns the value of it to the "var1" instance variable.
package test;

public class MyNewClass {
private String var1;

public MyNewClass(String para1)
 {
var1 = para1;
// or this.var1= para1;
}
}

Create a new method "doSomeThing" in class which do not return a value and has no parameters
package test;

public class MyNewClass {
private String var1;

public MyNewClass(String para1)
 {
var1 = para1;
// or this.var1= para1;
}

public void doSomeThing() {

}

}

Create a new method "doSomeThing2" in class which do not return a value and has two parameters, a int and a Person
package test;

public class MyNewClass {
private String var1;

public MyNewClass(String para1)
 {
var1 = para1;
// or this.var1= para1;
}

public void doSomeThing() {

}

public void doSomeThing2
(int a, Person person) {

}

}

Create a new method "doSomeThing2" in class which do return an int value and has three parameters, two Strings and a Person
package test;

public class MyNewClass {
private String var1;

public MyNewClass(String para1)
 {
var1 = para1;
// or this.var1= para1;
}

public void doSomeThing() {

}

public void doSomeThing2(int a, 
Person person) {

}

public int doSomeThing3
(String a, String b,
 Person person) {
return 5; // Any value will do 
for this example
}

}

Create a class "MyOtherClass" with two instance variables. One will store a String, the other will store a Dog. Create getter and setter for these variables.
package test;

public class MyOtherClass {
String myvalue;
Dog dog;

public String getMyvalue() {
return myvalue;
}

public void setMyvalue
(String myvalue) {
this.myvalue = myvalue;
}

public Dog getDog() {
return dog;
}

public void setDog(Dog dog) {
this.dog = dog;
}
}



9.2. Working with local variable

A local variable must always be declared in a method.


Table 4. 
What to do How to do it
Declare a (local) variable of type string. String variable1;
Declare a (local) variable of type string and assign "Test" to it. String variable2 = "Test";
Declare a (local) variable of type Person Person person;
Declare a (local) variable of type Person, create a new Object and assign the variable to this object. Person person = new Person();
Declare a array of type String String array[];
Declare a array of type Person and create an array for this variable which can hold 5 Persons. Person array[]= new Person[5];
Assign 5 to the int variable var1 (which was already declared); var1 = 5;
Assign the existing variable pers2 to the exiting variable pers1; pers1 = pers2;
Declare a ArrayList variable which can hold objects of type Person ArrayList<Person> persons;
Create a new ArrayList with objects of type Person and assign it to the existing variable persons persons = new ArrayList<Person>();
Declare a ArrayList variable which can hold objects of type Person and create a new Object for it. ArrayList<Person> persons = new ArrayList<Person>();

1 comment:

  1. Thank's sir .It is very nice tutorial for java beginner i read and understand each and every thing .Please provide the more program related to java.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...