1. Java Overview.
Java Programming formally appeard in 1995 designed by Sun Microsystems. Java generally refers to a combination of three things: the Java programming language (a high-level, object-oriented programming language); the Java Virtual Machine (a high-performance virtual machine that executes bytecodes on a specific computing platform, typically abbreviated JVM); and the Java platform, a JVM running compiled Java bytecodes, usually calling on a set of standard libraries such as those provided by Java Standard Edition (SE) or Enterprise Edition (EE).
Java is a simple programming language. Rather than saying that this is the feature of Java, we can say that this is the design aim of Java. When Java is developed, they wanted it to be simple because it has to work on electronic devices, where less memory is available. Now, the question is how Java is made simple? First of all, the difficult concepts of C and C++ have been omitted in Java. For example, the concept of pointers-which is very difficult for both learners and programmers, has been completely eliminated from Java. Next, JavaSoft (the team who developed Java is called with this name) people maintained the same syntax of C and C++ in Java, so that a programmer who knows C or C++ will find Java already familiar.
Note: Pointers have been eliminated from Java because it can crash a program easily in a case like adding two pointers, or forgetting to free memory allotted to variable and pointers can break security
Java is an object -oriented programming language. Java programs use objects and classes. What is an object? An object is anything that really exists in the world and can be distinguished from others. Everything that we see physically will come into this definition, for example, every human being, a book, a tree etc.
Java History
In 1990, Sun Microsystems Inc. has conceived a project to develop software for consumer electronic devices that could be controlled by a remote. This project was called Stealth Project but later its name was changed to Green Project.
In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patric Naughton, and several others met in Aspen, Colorado to discuss this project. Mike Sheradin was to focus on business development; Patrick Naughton was to begin work on the graphics system; and James Gosling was to identify the proper programming language for the project. Gosling thought C and C++ could be used to develop the project. But the problem he faced with them is that they were system dependent languages and hence could not be used on various processors, which the electronic devices might use. So he started developing a new language. This language was called Oak which was registered by some other company, later it was changed to Java.
Why the name Java? James Gosling and his team members were consuming a lot of tea while developing this language.
They felt that they were able to develop a better language because of the good quality tea they had consumed. So the tea also had its own role in developing this language and hence, they fixed the name for the language as Java. Thus, the symbol of Java is tea cup and saucer.
By September of 1994, Naughton and Jonathan Payne started writing WebRunner-1 Java-based Web browser, which was later renamed as HotJava. By October 1994, HotJava was stable and was demonstrated to Sun executives. HotJava was the first browser, having the capabilities of executing applets, which are programs designed to run dynamically on Internet. This time, Java's potential in the context of the World Wide Web was recognized.
Sun formally announced Java and HotJava at SunWorld conference in 1995. Soon after, Netscape Inc. announced that it would incorporate Java support in its browser Netscape Navigator. Latter, Microsoft also announced that they would support Java in their Internet Explorer Web browser, further solidifying Java's role in the World Wide Web. On January 23rd 1996, JDK 1.0 version was released. Today more than 4 million developers use Java and more than 1.75 billion devices run Java.javaSansar
You will need JavaScript enabled on your browser. We'll be compiling and running Java programs, so you'll need a Java development environment, such as the Java SDK. You can download SDK for free from Sun Microsystems website and a simple text editor, such as Notepad in Windows or vi in a UNIX environment. This tutorial will walks you through step by step procedure and gives you tools you need to start learning Java Programming and creating your first java program. Have the following lists ready before starting to program in java.
a) How to Download Java SE? Click Here
-Make sure you grab "Java SE Development Kit (JDK)" from the above link.
-Verify that JDK is installed in your computer. Go to DOS command line.
-Start>Run, type cmd in the 'Run window'
-Change directory to C:\Program Files\java (default folder)
-Type dir command.
-Installed JDK will appear in the list such as:
Jdk1.0.6_03
Jre1.5.0_04
b) How to set the Environment Path Variables?
It is more convenient to set the path variables to run the JDK executables (javac.exe, java.exe, javadoc.exe, etc.). If you don't set the PATH variable, you need to specify the full path to the executable every time you run it. Now you have successfully installed JDK in your computer and its time to set the environment path variables. to set the PATH permanently, add the full path of the jdk1.6.0_
-Click Advanced > Environment Variables.
-Click New and provide name and value.
-Name = JAVAPath
-Value = C:\Program Files\Java\jdk1.6.0_10\bin
The new path takes effect in each new command window you open after setting the PATH variable.
c) How to get a text Editor?
Obviously, depending on your choice, you can use any word processing editors. There are many text editors available out there. Most of the OSs comes with the notepad included in the system. Now let's use a simple Notepad editor in our tutorial.
First step towards our goal is:
- writing code (creating source file".java")
- compiling it into bytecode (.class file) and
- running the bytecode
public class MyFirstProgram { public static void main(String args[]) { System.out.println("My First Java Program"); }//End of main method }//End of the class |
-When you save the file, make sure to give the same exact filename as the class name of your program i.e. myFirstProgram.java. Please do not forget to give dot java (.java) extension after the filename.
-Open DOS Command
-Navigate to the folder where you had saved the program file (C:\java)
-Type "javac MyFirstProgram.java" and Hit Enter.
If you do not get an exception error, that means you have just compiled your source code to .class file
-Type "java MyFirstProgram" (no extension please) and hit Enter
If you see "My First Java Program" printed out in the command line, then congratulations. You've just written your first java program successfully.
javac: Java Compiler converts java code into byte code
java: Java Interpreter executes java bytecode from class file
3. Naming Conventions in Java.
Naming Convention is the rules followed by java programmers while writing the names of packages, classes, methods etc.
Names | Case | Examples |
---|---|---|
packages | lowercase | mydomain.com |
files | lowercase | .java |
classes | CapitalizedWithInternalWordsAlsoCapitalized | MyClass |
Exception class | ClassNameEndsWithException | ClassNotFoundException |
Interface | InterfaceNameEndsWithIfc | mydomain.com |
constants | UPPER_CASE_WITH_UNDERSCORES | DAYS_IN_WEEK |
private/protected | firstWordLowerCaseButInternalWordsCapitalized | myVar |
local variables | firstWordLowerCaseButInternalWordsCapitalized | myVar |
methods | firstWordLowerCaseButInternalWordsCapitalized | eatFast |
4. Data Type in Java.
Java comes with its standard data types which represents data such as integer numbers. We need variables to store the data. A variable represents a memory location which holds data. Following table represents all the data types available in java programming.
Data Type | Memory Size & Values |
---|---|
byte | 1 bytes, signed (two's complement), Covers values from -128 to 127 |
short | 2 signed byte (two's complement). Covers values from -32,768 to 32,767 |
int | 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647 |
long | 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 |
float | 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative) |
double | 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative) |
char | 2 bytes, unsigned, Unicode, 0 to 65,535 |
5. Operators in Java.
Operators are very important part of java programming. If a programmer needs to add two numbers, then he would use addition '+' sign. Such symbols or signs are call operators. Operators are used to manipulate data types. Operators work based on the operator precedence order, the higher the precedence will be evaluated first such as multiplication and division is evaluated first than addition or subtraction.
Operator | Meaning | Exampls | Result |
---|---|---|---|
+ | Addition | x+y | 15 |
- | Subtraction | x-y | 7 |
* | Multiplication | x*y | 49 |
/ | Division | x/y | 2.5 |
% | Modulus | x%y | 2 |
Operator Type | Symbols |
---|---|
Assignment Operator | = |
Arithmetic Operator | +, -, *, /, ++, --, % |
Relation Operator | <, >, <=, >=, ==, != |
Logical Operator | &&, ||, &, |, !, ^ |
Bitwise Operator | &, |, ^, > >, > > > |
Compound Asssignment Operator | +=, -=, *=, /=, %= |
Conditional Operator | ?: |
6. Control Statements in Java.
In Java programming, Sequential statements and Control statement are very popular. Sequential statements are executed one by one whereas Control Statements executed randomly and repeatedly. The following statement is what we call sequential statements.
System.out.println("My Java Program"); a=b+c; System.out.println(a); |
if …else statement do …while loop while loop for loop for-each loop switch statement break statement continue statement return statement |
If …else statement is used to perform if given condition is true or false. For example let's take a look into following snippet.
public class MyClassOne{ public static void main(String args[]){ int num=3; if(num==0) //condition1 { System.out.println("This is 0"); //statement1 } else if(num>0) //condition2 { System.out.println("The correct number is: "+num); //statement2 } else { System.out.println("You entered wrong number"); } } } |
Do…While Loop
If we need to repeatedly execute a group of statements, then we use do…while loop. If the condition is not true, the repetition will be stoped. Let's say we want to write a program to print numbers from 1 to 10. Here is the snippet.
public class MyProgram{ public static void main(String args[]){ int a; a=1; //beginning number is 1 do{ System.out.println(a); a++; }while(a<=10); } } |
While Loop
while loop works just like do…while loop. The only difference is that 'do…while' loop executes statement first and condition is tested later
public class MyProgram{ public static void main(String args[]){ Int a; a=1; //beginning number is 1 while(a<=10){ System.out.println(a); a++; } } } |
for loop works just like 'while loop' or 'do…while' loop but for loop repeats for the specified number of time and while loop repeats as long as certain condition is true.
public class MyProgram{ public static void main(String args[]){ for(int a=1; a<=10; x++); System.out.println(x); } } |
'for-each' loop is designed to handle the elements of a collection. Collection represents a group of elements. For example java.util package can be considered as a collection. 'for-each' loop repeatedly executes a group of statements for each element of the collection. It executes as many times as there are number of elements in the collection.
Switch Statement
When there are several options and we have to choose only one options from the available ones, we can use switch statement.
public class MyProgram{ public static void main(String args[]){ char color = 'g'; //color is set to 'g' switch(color) { case 'r': System.out.println("Red"); break; case 'g': System.out.println("Green"); break; case 'b': System.out.println("Blue"); break; case 'w': System.out.println("White"); break; default: System.out.println("No Color"); } } } |
'return' statement is used in the method. A method is executed when called from another method. The first method that is executed in a Java program by JVM is main() method and hence if we want to execute any other method we should call it from main(). 'return' statement is used in a method to come out of it to the main() method. Suppose if we want to call a method by the name of myMethod() from the main method. If return is used inside myMethod(), we can also return some value to the main() method. return 1; //returns 1 to calling method main()
return x; //returns x value to calling method main()
return -5; //returns -5
We will write a program that will return a value from a method
public class MyProgram{ public static void main(String args[]){ //call myMethod() and catch the result into sum. //since myMethod() is static, we can call int using classname.methodname() int sum = MyProgram.myMethod(10); //display the result now System.out.println("Result: "+sum); } //this method caluculates square value and returns it to main() static int myMethod(int num){ return num*num;//return square value to main method } } |
7. Inputs & Output in Java.
Input and Output both are often data but only difference is Input represent data given to a program and output represents data displayed as a result of a prgram execution. Let us take following example:
int a=10; int b=12; int c=a+b; System.out.println(c);In the above code snippet, what we see is inputs given are only 10 and 12. when you execute it, it will display only the sum of a+b. What if we want to accept these numbers from keyboard and a stream is required to accept input from keyboard. There are two type of streams input stream and output stream. stream carries data from one place to another. All streams are represented by classes in "java.io" package. System class is available in java.lang package and System class has following fields:
a) System.in: This represents InputStream object which by default represents standard input device i.e. keyboard
b) System.out: This represents PrintStream object, which by default represents standard output device, i.e. monitor
c) System.err: This field also represents PrintStream object, which by default represents monitor and is used to display error message. Now, its time to enter input from keyboard and display output in the monitor. Let us see the following code snippet:
import java.io.*; public class Accept{ public static void main(String arg[]) throws IOException { //create a BufferedReader object to accept data from keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Ask for char and read it System.out.print("Enter a character: "); char ch = (char)br.read(); //display the character System.out.println("You have entered: " +ch); } } |
An array represents group of elements of same data type. It can store a group of elements such that we can store a group of int values in the array. What we need to understand is that using arrays will simplify the programming by replacing a lot of statements by just one or two statements. There are two types of arrays:
a) Single Dimensional Arrays (1D Array)
Single dimensional array represents a single row or column of elements. For instance grades obtained by a student in 5 different
subjects. To represent one dimensional array, we use single squar braket"[]". There is two ways to create one dimentional array
int grades[] = {55, 65, 75, 85, 95}; //declare grades[] and initialize with 5 elements
or
int grades[] = new int[5]; grades[0]=55; grades[0]=65; grades[0]=75; grades[0]=85; grades[0]=95;Let us create a code snippet for one dimensional array using first method
public class MyArray { public static void main(String args[]) { int grades[] = {55, 65, 75, 85, 95}; for(int i=0; i<5; i++) { System.out.println(grades[i]); } } } |
Multi Dimensional Arrays represents 2D, 3D,...arrays which are combinations of several arrays. For instance, a two dimensional array is a combination of two or more 1D arrays whereas 3D arrays are combination of two or more dimensional arrays. Let us write a code snippet for grades obtained by a student previously in 5 different subjects. Now we will have 3 students and 5 different courses for each in two dimensional arrays.
public class MyArrayOneD { public static void main(String args[]) { int grades[] []= {{55, 65, 75, 85, 95}, {56, 66, 76, 86, 96}, {57, 67, 77, 87, 97}}; for(int i=0; i<3; i++)//rows { for(int j=0; j<5; j++)//columns { System.out.print(grades[i][j]+"\t"); } System.out.println();//next line } } } |
public class MyArrayOneD{ public static void main(String args[]){ int grades[] []; grades= new int[3][5]; grades[0][0]=55; grades[0][1]=65; grades[0][2]=75; grades[0][3]=85; grades[0][4]=95; grades[1][0]=56; grades[1][1]=66; grades[1][2]=76; grades[1][3]=86; grades[1][4]=96; grades[2][0]=57; grades[2][1]=67; grades[2][2]=77; grades[2][3]=87; grades[2][4]=97; for(int i=0; i<3; i++)//rows { for(int j=0; j<5; j++)//columns { System.out.print(grades[i][j]+"\t"); } System.out.println();//next line } } } |
1 comment:
Test comment.
Post a Comment