Monday 26 November 2012

Java Programming - Basics of Java

Java Programming -Basics of Java


Structure:

 2.1 Introduction
    Objective
2.2 Keywords
2.3 How does it work?
    Self Assessment Questions
2.4 How to include comments
    Self Assessment Questions
2.5 Data Types in Java
2.5.1 Primitives Data Types
2.5.2 Abstract/Derived Data Types
      Self Assessment Questions
2.6 Variables in Java
2.6.1 Naming Variables
      Self Assessment Questions
2.7 Using classes in java
2.7.1 Standard for coding
      Self Assessment Questions
2.8 Declaring methods in java
      Self Assessment Questions
2.9 Code to display Test Value
2.10 The main method
2.11 Invoke methods
     Self Assessment Questions
2.12 How to Save a Java Program
2.13 Compiling Java Programs
2.14 Executing a Java Program
2.15 Summary
2.16 Terminal Questions
     
     Java Programming Unit 2

2.1 Introduction
The English language has a vocabulary – a set of words that have certain meaning. It also provides us with rules for using the vocabulary – English grammar. The Java language also provides a vocabulary and a set of rules to use the vocabulary. The vocabulary is representedthrough a set of keywords and the grammar is the syntax of the language.
This lesson explains how to write object-oriented program using the Java language syntax.
Objectives
In this chapter, you will learn about the:
 
  Java Keyword
  Data types in Java
  Variable naming conventions
  Initializing Variables.
  Literals
2.2 Keywords
Keywords are special words that are of significance to the Java compiler. You cannot use keywords to name classes or variables. The table below contains a list of Java keywords.
Abstract
boolean
break
byte
case
Catch
Char
Class
const
continue
Default
Do
Double
else
extends
Final
Finally
Float
for
Goto
If
Implements
Import
instanceof
Int
interface
Long
Native
new
Package
Private
protected
Public
return
Short
Static
Super
Switch
synchronized
This
Throw
throws
Transient
try
Void
Volatile
While
Java Programming Unit 2
2.3 How does it work?
A compiler converts the Java program into an intermediate language representation called Bytecode which is platform independent. A Java file will have the extension .java, similar toa word file having the extension .doc, a pascal file has the extension .pas and a text filehas the extension .txt.
Let us assume there exists a Java file named Hello. java. When this file is complied we geta file called as Hello. class
This class file is run using an interpreter as and when necessary. The figure 2.1 shows thejava program saved as Hello. java

The step of compiling and running the program is shown in figure 2.2. The program is storedin a subdirectory called java. The above program when run prints the message “Hello! How are you? “
Java Programming Unit 2


The concept of “write once, run anywhere” is possible in Java. The Java program can be compiled on any platform having a Java compiler. The resulting bytecodes can then be run on Window NT or Solaris or Macintosh or any other machine. The machine should have a Java platform to run Java code. Java platform consists of Java Virtual Machine (JVM) and a package of ready made software components. This package is known as The Java Application Programming Interface (Java AP!). The compiled Java program can run on any hardware platform having Java Virtual Machine (JVM) installed on it.
Self Assessment Questions
1. A compiler converts the Java program into an intermediate language representation called ____________.
2. The concept of _________________ is possible in Java.
2.4 How to include comments
Comments can be included in a Java program as follows:
Type 1
/* Comments go here
More comments here
*/
Type 2
// this information is ignored by the compiler till the end of the line.
Type 3
/* documentation comment */
In the first type comments can spread over multiple lines. In the second type the information written after // is ignored by the compiler. The third type of comment is used by a toolcalled javadoc for automatic generation of documentation.
Self Assessment Questions
1. The third type of comment is used by a tool called ___________ for automatic generation of documentation.
2.5 Data Types in Java
There are two kinds of data types in Java
Primitives/standard data types.
Abstract/derived data types.
2.5.1 Primitives Data Types
Primitive data types (also know as standard data types) are the data types that are built into the Java language. The Java compiler holds details instructions on each operation the data types that are built into the Java language. The Java compiler holds detailed instructions on each legal operation the data type supports. There are eight primitive data types inJava.
Data Type
Size/Format (bits)
Description
Range
byte
8
Byte-length integer
-128 to 128 (signed)
0 to 255 (unsigned)
short
16
Short integer
-215 to 215 -1
int
32
integer
-231 to 231 -1
long
64
Long integer
-263 to 263 -1
float
32
Single precision floating point
+/- about 1039
double
64
Double precision floating point
+/- about 10317
char
16
A single character
Boolean
1
A boolean value (true or false)
The data types – byte, short, int, long, float and double are numeric data types. The firstfour of these can hold only whole numbers whereas the last two (float and double) can hold decimal values like 5.05. All these data types can hold negative values. However, the keyword unsigned can be used to restrict the range of values to positive numbers. Amongst others, boolean can hold only the value true or false and char can hold only a single character.
2.5.2 Abstract/Derived Data Types
Abstract data types are based on primitives data types and have more functionality that theprimitive data types. For example, String is an abstract data type that can store alphabets, digits and other characters like /, (); :$#. You cannot perform calculations on a variable of the string data type even if the data stored in it has digits.
Self Assessment Questions
1. What are the different type of data types in java ?
Java Programming Unit 2
Sikkim Manipal University Page No. 19
2.6 Variables in Java
When you learned algebraic equations in school, you used x and y to represent values in equations. Unlike pi which has a constant value of 3.14, the values of x and y are not constant in equations. Java provides constants and variables to store data in programs.
Java allocates memory to each variable and constant you use in your program. As in algebra,the values of variables may change in a program, but the values of constants, as the name suggests, do not change. You must assign unique names to variables and constants. Variable names are used in a program in much the same way as they are in ordinary Algebra.
Each variable used in a program must be declared. That is to say, the program must contain a statement specifying precisely what kind of information (data type) the variable will contain. This applies to every variable used in the program, regardless of the type.
2.6.1 Naming Variables
A program refers to a variable using its name. Certain rules and conventions govern the naming of variables. You must adhere to rules. Conventions help improve the readability of theprogram, but following them is not mandatory.
Rules for Naming Variables in Java
A variable name:
 Must not be a keyword in Java.
 Must not begin with a digit.
 Must not contain embedded spaces.
 Can contain characters from various alphabets, like Japanese, Greek, and Cyrillic.

Syntax for Defining Variables
All the attributes of a class are defined as data members. The syntax used to declare a class variable is:
 
As the braces “{ }” are used to mark the beginning and end of a class, a semicolon “;” is used to mark the end of a statement.
Self Assessment Questions
1. What are the rules for naming variable in Java?
2.7 Using classes in java
The data members and methods of a class are defined inside the class body. In java, braces { } mark the beginning and end of a class or method.
Any program that you write in Java can be written using a simple text editor. We will use Windows Notepad for writing programs.
Public class Employee
{
}
2.7.1 Standard for coding
By following coding standards and conventions, you can write code that is easy to read and understand.
One of the conventions is indentation. Notice that the code written below clearly indicates the data members defined in the class.
public class Employee
{
String employeeName;
String employeeAddress;
}

2.8 Declaring methods in java
 ([argument_list])
{
}
access_specifier
An access specifier defines where a method can be accessed. A public specifier allows the method to be executed from another class. A private provides access to methods for only the current class.
return_type
The return_type of a method is the data type of the value that is returned by the method.
public void displayEmpName (); // returns no value, therefore, the return
// type of the method is void.
public float calculateAllowance (); // returns a value of float data type
// therefore, the return type of the method is „
// float
Self Assessment Questions
1. What do you mean by access specifier?
2.9 Code to display Test Value
The System class
To communicate with the computer, a program needs to use certain system resources such as the display device and the keyboard.
Java makes use of all these resources with the help of a class called System, which contains all the methods that are required to work with these resources.

System is one of the most important and useful classes provided by Java. It provides a standard interface to common system resources like the display device and the keyboard.
The out Object
It is an object encapsulated inside the System class, and represents the standard output device. This object contains the println () method.
The println () method
The println () method displays the data on the screen.
Example
System.out.println (“Hello World”);
Will display “Hello World” on the screen.
2.10 The main method
In a Java application, you may have many classes. Within those classes, you may have many methods. The method that you need to execute first should be the main () method.
Syntax for the main () method
Public static void main (String args [])
{
}
The main () method should exist in a class that is declared as public.
Rules for the main () method
The primary name of the file in which the code is written, and the name of the class that has the main () method should be exactly the same.
If you try to execute a Java application that does not have a main () method, the following error message will be printed:
Exception in thread “main” Java.lang.NoSuchMethodError: main

2.11 Invoke methods
Creating an Object of a class
The new operator is used to create a class object.
Example
Employee emp = new Employee ();
Invoking a Method
To invoke a method, the method name must be followed by parentheses and a semicolon. One method of a class can invoke another method of the same class using the name of the method.
Example
Public class Employee
{
String employeeName;
String employeeAddress;
Public Employee ()
{
employeeName=”Preetam”;
EmployeeAddress = “Orissa “;
}
public void display ()
{
System.out.println (“Name: “+employeeName);
System.out.println (“Address: “+ employeeAddress);
}
public static void main (String arg [])
{
Java Programming Unit 2
Sikkim Manipal University Page No. 24
Employee emp =new Employee ();
emp.display ();
}
}
Self Assessment Questions
1. _____________ operator is used to create an object.
2.12 How to Save a Java Program
The programs that you write in Java should be saved in a file, which has the following nameformat:

.java
2.13 Compiling Java Programs
A program is a set of instructions. In order to execute a program, the operating system needs to understand the language. The only language an operating system understands is in terms of 0‟s and 1‟s i.e. the binary language. Programs written in language such as C and C++ are converted to binary code during the compilation process. However, that binary code can be understood only by the operating system for which the program is compiled. This makes theprogram or application operating system dependent.
In Java, the program is compiled into bytecode (.class file) that run on the Java Virtual Machine, which can interpret and run the program on any operating system. This makes Java programs platform-independent.
At the command prompt, type
javac .java

2.14 Executing a Java Program
When the code is compiled and error-free, the program can be executed using the command:
java 
2.15 Summary
 Creating Classes Using Java
The data members and methods of a class are defined inside the class body. In java, braces {} mark the beginning and end of a class or method.
The class keyword is used to declare a class.
 Coding Methods of a class
Methods provide functionality to classes. In Java, methods are declared in the class body.

Declaring Objects
The new operator is used to create a class object.

Displaying Data on Screen
The System class is one of the most important and useful classes provided by java. It provides a standard interface to common system resources like the display device and the keyboard.
The println () method displays the data on the screen.
 Compiling a Java Program
In Java, the program is compiled into bytecode (.class file) that runs on the Java Virtual Machine, which can interpret and run the program on any operating system. This makes Java programs platform-independent.

 Executing a Java program
When the code is compiled and error-free, the program can be executed by issuing the following command:
java 
2.16 Terminal Questions
1. The Candidate class for the employee referral process has the following attributes and behaviors:
Candidate
CandidateName
CandidateAddress
CandidatePosition
displayDetails()
Create the candidate class with its attribute and methods.
2. What do you mean by the statement :
System.out.println(“ “);
3. How do you compile a Java program?
4. How do you execute a Java program?

11 comments:

  1. A service business, or one with delivery service, can get into trouble if the vehicle breaks down.
    Good news is: the ones opting for leasing cars online
    also enjoy special deals. You may also be charged at the
    end of your lease for excessive mileage, damages, and unusual wear-and-tear.


    Here is my web-site; Best Car Leasing Deals

    ReplyDelete
  2. I was wondering if you ever thought of changing the
    layout of your site? Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or two images.
    Maybe you could space it out better?

    Feel free to surf to my blog; graphic Design

    ReplyDelete
  3. Thanks for every other informative web site.
    Where else could I get that type of information
    written in such a perfect way? I have a project that I am just now operating on, and I've been at the glance out for such information.

    My blog post - business Furniture Cape town

    ReplyDelete
  4. I really love your site.. Great colors & theme. Did you develop this web site yourself?
    Please reply back as I'm wanting to create my own blog and want to find out where you got this from or just what the theme is named. Many thanks!

    Feel free to visit my blog :: golf holidays life style

    ReplyDelete
  5. I'll right away grasp your rss as I can't to find your e-mail subscription hyperlink or e-newsletter service.
    Do you've any? Please let me recognize in order that I may just subscribe. Thanks.

    My webpage :: ppe Johannesburg

    ReplyDelete
  6. It's very effortless to find out any topic on net as compared to books, as I found this paragraph at this website.

    My blog post - illustration Johannesburg

    ReplyDelete
  7. A person essentially help to make significantly posts I would state.
    That is the first time I frequented your web page and
    up to now? I amazed with the research you made to create
    this actual put up amazing. Magnificent activity!



    my web-site - building renovations Johannesburg architectural services Johannesburg

    ReplyDelete
  8. Gingko biloba has been dated back over two hundred million years and it's use as medicine goes back at least five thousand years. Medication: If tinnitus was originally caused by ear infection, medicine can be prescribed to treat the condition. The Chinese have practiced what we would now call alternative medicine and treatment for centuries.

    Here is my homepage; tinnitus remedies

    ReplyDelete
  9. Thanks for sharing such a good opinion, paragraph is good,
    thats why i have read it fully

    my web blog ... visit this hostgator site

    ReplyDelete
  10. The Toronto real estate agent suitably guides you right from the beginning.
    Indications are growing that investors will bring a rebirth of interest
    in property this spring. Just use the three principles you would for any business: buy
    at a price you can afford; sell for more than you paid, and sell in a measurable time frame.


    My webpage Asunto Vuokraus

    ReplyDelete
  11. Hi just wanted to give you a quick heads up and let you know a few of the pictures aren't loading correctly. I'm not sure why but I think its a linking issue.
    I've tried it in two different internet browsers and both show the same results.

    my web site :: visit this site

    ReplyDelete