Unit-I JAVA Fundamentals
1) OOP: Stands for "Object-Oriented Programming." OOP (not Oops!) refers to a programming methodology based on objects, instead of just functions and procedures. These objects are organized into classes, which allow individual objects to be group together. Most modern programming languages including Java, C/C++, and PHP, are object-oriented languages, and many older programming languages now have object-oriented versions..
An "object" in an OOP language refers to a specific type, or "instance," of a class. Each object has a structure similar to other objects in the class, but can be assigned individual characteristics. An object can also call functions, or methods, specific to that object. For example, the source code of a video game may include a class that defines the structure of characters in the game. Individual characters may be defined as objects, which allows them to have different appearances, skills, and abilities. They may also perform different tasks in the game, which are run using each object's specific methods.Object-oriented programming makes it easier for programmers to structure and organize software programs. Because individual objects can be modified without affecting other aspects of the program, it is also easier to update and change programs written in object-oriented languages. As software programs have grown larger over the years, OOP has made developing these large programs more manageable.
2) Basic Concepts of Object Oriented Programming(OOP):
i) Class: In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior. Data field members (member variables or instance variables) enable a class object to maintain state. Other kinds of members, especially methods, enable a class object's behavior. Class instances are of the type of the associated class.
ii)Object: In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure. (With the later introduction of object-oriented programming the same word, "object", refers to a particular instance of a class).
iii)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.
iv)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 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.
* Forces the user to use an interface to access data
* Makes the code more maintainable.
v)Inheritance
Inheritance is the process by which one object acquires the properties of another object.
vi)Polymorphism
Polymorphism is the existence of the classes or methods in different forms or single name denoting different
implementations.
implementations.
3) Benefits of OOPs:
- Reusability: In OOP’s programs functions and modules that are written by a user can be reused by other users without any modification.
- Inheritance: Through this we can eliminate redundant code and extend the use of existing classes.
- Data Hiding: The programmer can hide the data and functions in a class from other classes. It helps the programmer to build the secure programs.
- Reduced complexity of a problem: The given problem can be viewed as a collection of different objects. Each object is responsible for a specific task. The problem is solved by interfacing the objects. This technique reduces the complexity of the program design.
- Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones.
- Message Passing: The technique of message communication between objects makes the interface with external systems easier.
- Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods;
4) Applications of OOP:
OOP Provides Many Applications:-
Real time Systesm : -
A real time system is a system that give output at given instant and its parameters changes at every time. A real time system is nothing but a dynamic system. Dynamic means the system that changes every moment based on input to the system. OOP approach is very useful for Real time system because code changing is very easy in OOP system and it leads toward dynamic behaviour of OOP codes thus more suitable to real time system.
Simulation and Modelling: -
System modelling is another area where criteria for OOP approach is countable. Representing a system is very easy in OOP approach because OOP codes are very easy to understand and thus is preffered to represent a system in simpler form.
Hypertext And Hypermedia : -
Hypertext and hypermedia is another area where OOP approach is spreading its legs. Its ease of using OOP codes that makes it suitable for various media approaches.
Decision support system : -
Decision support system is an example of Real time system that too very advance and complex system. More details is explained in real time system.
CAM/CAE/CAD System : -
Computer has wide use of OOP approach. This is due to time saving in writing OOP codes and dynamic behaviour of OOP codes.
Office Automation System : -
Automation system is just a part or type of real time system. Embeded systems make it easy to use OOP for automated system.
AI and expert system : -
It is mixed system having both hypermedia and real time system.
Real time Systesm : -
A real time system is a system that give output at given instant and its parameters changes at every time. A real time system is nothing but a dynamic system. Dynamic means the system that changes every moment based on input to the system. OOP approach is very useful for Real time system because code changing is very easy in OOP system and it leads toward dynamic behaviour of OOP codes thus more suitable to real time system.
Simulation and Modelling: -
System modelling is another area where criteria for OOP approach is countable. Representing a system is very easy in OOP approach because OOP codes are very easy to understand and thus is preffered to represent a system in simpler form.
Hypertext And Hypermedia : -
Hypertext and hypermedia is another area where OOP approach is spreading its legs. Its ease of using OOP codes that makes it suitable for various media approaches.
Decision support system : -
Decision support system is an example of Real time system that too very advance and complex system. More details is explained in real time system.
CAM/CAE/CAD System : -
Computer has wide use of OOP approach. This is due to time saving in writing OOP codes and dynamic behaviour of OOP codes.
Office Automation System : -
Automation system is just a part or type of real time system. Embeded systems make it easy to use OOP for automated system.
AI and expert system : -
It is mixed system having both hypermedia and real time system.
5) Introduction to Java Programming:
Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++. Java originated at Sun Microsystems, Inc. in 1991. It was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was developed to provide a platform-independent programming language. This site gives you an Introduction to Java Programming accompanied with many java examples. Its a complete course in java programming for beginners to advanced java.
Platform independent
Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
Java Virtual Machine
6)What is the Java Virtual Machine? What is its role?
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.
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.
7)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. This site outlines the building blocks of java by stating few java examples along with some java tutorials.
Getting Started with Java:
Getting Java Basics quickly has become easy with Javabeginner.com. This site is for the java programmers who want to use the Java programming language to create applications using the Java basics. This site is for absolute beginners to advanced java programmers who do not require any prerequisite Java knowledge. For getting started with Java you’ll have to have some basic understanding of the concepts of programming.
After going through all the tutorials in this site, you would have learnt the essential concepts and features of the Java Programming Language which include exceptions, Swing GUI programming, Collections framework etc. A lot of code examples are used through out tutorial to make you understand the language better.
All the listings and programs in the website are compiled and run using the JDK 1.5.
Download : JDK and JRE 1.5
All the listings and programs in the website are compiled and run using the JDK 1.5.
Download : JDK and JRE 1.5
8)Java Architecture
The Java environment is composed of a number of system components. You use these components at compile time to create the Java program and at run time to execute the program. Java achieves its independence by creating programs designed to run on the Java Virtual Machine rather than any specific computer system.
- After you write a Java program, you use a compiler that reads the statements in the program and translates them into a machine independent format called bytecode.
- Bytecode files, which are very compact, are easily transported through a distributed system like the Internet.
- The compiled Java code (resulting byte code) will be executed at run time.
Java programs can be written and executed in two ways:
- Stand-alone application (A Java Swing Application)
- Applet which runs on a web browser (Example: Internet Explorer)
9)Java source code:
A Java program is a collection of one or more java classes. A Java source file can contain more than one class definition and has a .java extension. Each class definition in a source file is compiled into a separate class file. The name of this compiled file is comprised of the name of the class with .class as an extension. Before we proceed further in this section, I would recommend you to go through the ‘Basic Language Elements’.
Below is a java sample code for the traditional Hello World program. Basically, the idea behind this Hello World program is to learn how to create a program, compile and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}//End of main
}//End of HelloWorld Class
|
Output
Hello World
ABOUT THE PROGRAM
I created a class named “HelloWorld” containing a simple main function within it. The keyword class specifies that we are defining a class. The name of a public class is spelled exactly as the name of the file (Case Sensitive). All java programs begin execution with the method named main(). main method that gets executed has the following signature : public static void main(String args[]).Declaring this method as public means that it is accessible from outside the class so that the JVM can find it when it looks for the program to start it. It is necessary that the method is declared with return type void (i.e. no arguments are returned from the method). The main method contains a String argument array that can contain the command line arguments. The brackets { and } mark the beginning and ending of the class. The program contains a line ‘System.out.println(”Hello World”);’ that tells the computer to print out on one line of text namely ‘Hello World’. The semi-colon ‘;’ ends the line of code. The double slashes ‘//’ are used for comments that can be used to describe what a source code is doing. Everything to the right of the slashes on the same line does not get compiled, as they are simply the comments in a program.
Java Main method Declarations
class MainExample1 {public static void main(String[] args) {}}
class MainExample2 {public static void main(String []args) {}}
class MainExample3 {public static void main(String args[]) {}}
class MainExample2 {public static void main(String []args) {}}
class MainExample3 {public static void main(String args[]) {}}
All the 3 valid main method’s shown above accepts a single String array argument.
10)Compiling and Running an Application:
To compile and run the program you need the JDK distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries and packages, and tools. Download an editor like Textpad/EditPlus to type your code. You must save your source code with a .java extension. The name of the file must be the name of the public class contained in the file.
Steps for Saving, compiling and Running a Java
Step 1:Save the program With .java Extension.
Step 2:Compile the file from DOS prompt by typing javac <filename>.
Step 3:Successful Compilation, results in creation of .class containing byte code
Step 4:Execute the file by typing java <filename without extension>
Step 2:Compile the file from DOS prompt by typing javac <filename>.
Step 3:Successful Compilation, results in creation of .class containing byte code
Step 4:Execute the file by typing java <filename without extension>
11)Java Development Kit:
The Java Developer’s Kit is distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries and packages, and tools
javadoc
The javadoc tool provided by Sun is used to produce documentation for an application or program,
Jar Files
A jar file is used to group together related class files into a single file for more compact storage, distribution, and transmission.
PATH and CLASSPATH
The following are the general programming errors, which I think every beginning java programmer would come across. Here is a solution on how to solve the problems when running on a Microsoft Windows Machine.
1. ‘javac’ is not recognized as an internal or external command, operable program or batch file
When you get this error, you should conclude that your operating system cannot find the compiler (javac). To solve this error you need to set the PATH variable.
How to set the PATH Variable?
Firstly the PATH variable is set so that we can compile and execute programs from any directory without having to type the full path of the command. To set the PATH of jdk on your system (Windows XP), add the full path of the jdk<version>\bin directory to the PATH variable. Set the PATH as follows on a Windows machine:
a. Click Start > Right Click “My Computer” and click on “Properties”
b. Click Advanced > Environment Variables.
c. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value for PATH is:
b. Click Advanced > Environment Variables.
c. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value for PATH is:
C:\jdk<version>\bin (jdk<version is nothing but the name of the directory where jdk is installed)
If there are already some entries in the PATH variable then you must add a semicolon and then add the above value (Version being replaced with the version of JDK). The new path takes effect in each new command prompt window you open after setting the PATH variable.
2. Exception in thread “main” java.lang.NoClassDefFoundError: HelloWorld
If you receive this error, java cannot find your compiled byte code file, HelloWorld.class.If both your class files and source code are in the same working directory and if you try running your program from the current working directory than, your program must get executed without any problems as, java tries to find your .class file is your current directory. If your class files are present in some other directory other than that of the java files we must set the CLASSPATH pointing to the directory that contain your compiled class files.CLASSPATH can be set as follows on a Windows machine:
a. Click Start > Right Click “My Computer” and click on “Properties”
b. Click Advanced > Environment Variables.
b. Click Advanced > Environment Variables.
Add the location of classes’ folder containing all your java classes in User Variables.
If there are already some entries in the CLASSPATH variable then you must add a semicolon and then add the new value . The new class path takes effect in each new command prompt window you open after setting the CLASSPATH variable.
Java 1.5
The Java 1.5 released in September 2004.
Goals
Less code complexity
Better readability
More compile-time type safety
Some new functionality (generics, scanner)
Better readability
More compile-time type safety
Some new functionality (generics, scanner)
New Features
Enhanced for loop
Enumerated types
Autoboxing & unboxing
Generic types
Scanner
Variable number of arguments (varargs)
Static imports
Annotations
Enumerated types
Autoboxing & unboxing
Generic types
Scanner
Variable number of arguments (varargs)
Static imports
Annotations
Basic Language Elements:
This part of the java tutorial teaches you the basic language elements and syntax for the java programming language. Once you get these basic language concepts you can continue with the other object oriented programming language concepts.12)Keywords:
There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case.Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
|
/** This class is a Hello World Program used to introduce
the Java Language*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println(”Hello World”); //Prints output to console
}
}
For more information on different Keywords - Java Keywords
Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related to
the C programming language. const and goto are Java keywords. The word finalize is the name of a method
of the Object class and hence not a keyword. enum and label are not keywords.
13)Comments:
Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program.
Java supports three comment styles.
Block style comments begin with /* and terminate with */ that spans multiple lines.Line style comments begin with // and terminate at the end of the line. (Shown in the above program)
Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program)
name of this compiled file is comprised of the name of the class with .class as an extension.
Variable, Identifiers and Data Types
14)Variables:Variables are used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope of the Java program. Variables have a data type, that indicates the kind of value they can store. Variables declared inside of a block or method are called local variables; They are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.
public class localVariableEx {
public static int a;
public static void main(String[] args) {
int b;
System.out.println("a : "+a);
System.out.println("b : "+b); //Compilation error
}}
|
15) Data type:
Data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types.
Java has four main primitive data types built into the language. We can also create our own data types.
· Integer: byte, short, int, and long.
· Floating Point: float and double
· Character: char
· Boolean: variable with a value of true or false.
The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.
Data Type
|
Default Value (for fields)
|
Range
|
Byte
|
0
|
-127 to +128
|
Short
|
0
|
-32768 to +32767
|
Int
|
0
| |
Long
|
0L
| |
Float
|
0.0f
| |
double
|
0.0d
| |
Char
|
‘\u0000′
|
0 to 65535
|
String (object)
|
null
| |
boolean
|
false
|
For Example
String message = “hello world”In the above statement, String is the data type for the identifier message. If you don’t specify a value when the variable is declared, it will be assigned the default value for its data type.
Identifier Naming Rules
- Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.
- Must begin with a letter, dollar sign, or an underscore
- Are case sensitive
- Keywords cannot be used as identifiers
- Within a given section of your program or scope, each user defined item must have a unique identifier
- Can be of any length.
16)The scope of a variable : is the part of the program over which the variable name can be referenced. (from Ivor Horton's Beginning Java 2, JDK 5 Edition by Ivor Horton)
You cannot refer to a variable before its declaration.
You can declare variables in several different places:
- In a class body as class fields. Variables declared here are referred to as class-level variables.
- As parameters of a method or constructor.
- In a method's body or a constructor's body.
- Within a statement block, such as inside a while or for block.
Variable scope refers to the accessibility of a variable.
The rule 1 is that variables defined in a block are only accessible from within the block. The scope of the variable is the block in which it is defined. For example, consider the following for statement.
public class MainClass {
public static void main(String[] args) { for (int x = 0; x < 5; x++) { System.out.println(x); } } } |
Rule number 2 is a nested block can access variables declared in the outer block. Consider this code.
public class MainClass {
public static void main(String[] args) { for (int x = 0; x < 5; x++) { for (int y = 0; y < 3; y++) { System.out.println(x); System.out.println(y); } } } } |
Variables declared as method parameters can be accessed from within the method body. Class-level variables are accessible from anywhere in the class.
If a method declares a local variable that has the same name as a class-level variable, the former will 'shadow' the latter. To access the class-level variable from inside the method body, use the this keyword.
17)Variable Scope in a block:
| |
| |
inner = 2
outer = 1
inner = 3
outer = 1
|
18)
Command Line Arguments in Java Program:
Java application can accept any number of arguments directly from the command line. The user can enter command-line arguments when invoking the application. When running the java program from java command, the arguments are provided after the name of the class separated by space. For example, suppose a program named CmndLineArguments that accept command line arguments as a string array and echo them on standard output device.
java CmndLineArguments Mahendra zero one two three
|
/**
* How to use command line arguments in java program. */ class CmndLineArguments { public static void main(String[] args) { int length = args.length; if (length <= 0) { System.out.println("You need to enter some arguments."); } for (int i = 0; i < length; i++) { System.out.println(args[i]); } } } |
Run program with some command line arguments like:
java CmndLineArguments Mahendra zero one two three
OUTPUT Command line arguments were passed : Mahendra zero one two three |
19)Symbolic Constants in Java:
symbolic constants are named constants
like :
final double PI = 3.14 ;
They are constants because of the 'final' keywords, so they canNOT be reassigned a new value after being declared as final
And they are symbolic , because they have a name
A NON symbolic constant is like the value of '2' in expression
int foo = 2 * 3
like :
final double PI = 3.14 ;
They are constants because of the 'final' keywords, so they canNOT be reassigned a new value after being declared as final
And they are symbolic , because they have a name
A NON symbolic constant is like the value of '2' in expression
int foo = 2 * 3
20)Type Casting: refers to changing an entity of one datatype into another. This is important for the type conversion in developing any application. If you will store a int value into a byte variable directly, this will be illegal operation. For storing your calculated int value in a byte variable you will have to change the type of resultant data which has to be stored. This type of operation has illustrated below :
In this example we will see that how to convert the data type by using type casting. In the given line of the code c = (char)(t?1:0); illustrates that if t which is boolean type variable is true then value of c which is the char type variable will be 1 but 1 is a numeric value. So, 1 is changed into character according to the Unicode value. But in this line c = (char)(t?'1':'0'); 1 is already given as a character which will be stored as it is in the char type variable c.
Code of the program :
public class conversion{
public static void main(String[] args){ boolean t = true; byte b = 2; short s = 100; char c = 'C'; int i = 200; long l = 24000; float f = 3.14f; double d = 0.000000000000053; String g = "string"; System.out.println("Value of all the variables like"); System.out.println("t = " + t ); System.out.println("b = " + b ); System.out.println("s = " + s ); System.out.println("c = " + c ); System.out.println("i = " + i ); System.out.println("l = " + l ); System.out.println("f = " + f ); System.out.println("d = " + d ); System.out.println("g = " + g ); System.out.println(); //Convert from boolean to byte. b = (byte)(t?1:0); System.out.println("Value of b after conversion : " + b); //Convert from boolean to short. s = (short)(t?1:0); System.out.println("Value of s after conversion : " + s); //Convert from boolean to int. i = (int)(t?1:0); System.out.println("Value of i after conversion : " + i); //Convert from boolean to char. c = (char)(t?'1':'0'); System.out.println("Value of c after conversion : " + c); c = (char)(t?1:0); System.out.println("Value of c after conversion in unicode : " + c); //Convert from boolean to long. l = (long)(t?1:0); System.out.println("Value of l after conversion : " + l); //Convert from boolean to float. f = (float)(t?1:0); System.out.println("Value of f after conversion : " + f); //Convert from boolean to double. d = (double)(t?1:0); System.out.println("Value of d after conversion : " + d); //Convert from boolean to String. g = String.valueOf(t); System.out.println("Value of g after conversion : " + g); g = (String)(t?"1":"0"); System.out.println("Value of g after conversion : " + g); int sum = (int)(b + i + l + d + f); System.out.println("Value of sum after conversion : " + sum); } } |