Showing posts with label JAVA FUNDAMENTALS. Show all posts
Showing posts with label JAVA FUNDAMENTALS. Show all posts

Java Arrays Programming for beginners

Java arrays are objects.

In arrays we can store multiple variables of same type that are referred by a common name.
An array is always an object,even if the array is declared to hold object references or primitives .

In array variables are placed in indexed order.These variables are called elements of an array. So in java arrays we can access the elements or values through the index.Every element in an array is just a variable.

Now we have to know how to declare the array ,creation of array and accessing the elements from array.

Declaration of arrays are in two forms:

form1: type arrayname[]; Type followed by name of the array,followed by Square bracket .

ex: int abc[];

form2: type[] arrayname; Type followed by bracket,followed by name of the array.

ex: float[] abc;

form2 is the recommended way,because name is clearly separated from the type.

At the time of declaration, we should not enter the size of an array.violation leads to compile time exception.

for example int[5] a; it gives compile time exception.

After declaration of an array ,we can't put any other data type except the declared array type.
but implicitly promoted data types we can use, means less than the declared array type.for
example int[] x, the allowed data types are byte,short,char,int.

After creation of java arrays,once you fix the size of an array,we can't change the size of an array.But you can change an individual array element. If it is need to change the array size frequently while the program is running then we should go for another concept, known as Arraylist.

In java arrays are work differently than they do in c,c++.

creation of java arrays:

After declaring an array,we need to put it into memory.arrays must be declared in the memory before they are used.

Java arrays are creating only using new keyword .

array type[] array name=new array type[size];

Ex: int[] x=new int[50];

Array type is int , the allowed data types are byte/short/char/int.
This statement sets up an array that can hold 50 integers means 0 to 49 ,not 1 to 50 .

At the time of creation we must specify the size, otherwise compile time exception occurs.Even
we can give zero number also.but we can't specify the size with negative number we will get Run time Exception(RTE).we have to use integer to specify the size violation leads to compile time exception.

for example:

int[] x = new int[55]; It is OK

int[] x = new int[0]; It is OK

int[] x = new int[]; it gives compile time exception.

int[] x = new int[-5]; RTE, Negative Array Size Exception

int[] x = new int[9.5]; CTE,Possible loss of precission

we can write declaration and creation separately like this,

int[] x;

x=new int[8];

If you want to find the number of elements of an array, use arrayName.length.

For example :

for (int i = 0; i < style="font-weight: bold; color: rgb(51, 51, 255);">

Initialization of Arrays:

Once an array is created,all the elements will assign with default values based on declared data type.

For example : for int default value is zero.
for string default value is null.
for Boolean default value is false.

java arrays are created starting with a subscript of zero and ends with a value one lessthan the size declared.

In java arrays the declaration,creation and initialization in a single line is possible.
for this syntax, specify the declaration and size,later we can give the values at run time.

int a[];

a=new int[5];

a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;

Instead of above declaration,creation and initialization we can write like this,

int[] a={10,20,30,40,50};

But for this syntax, at the time of declaration we must know the array size and initialization values,can't give the values at run time.

It is possible to convert an array object to another array,but the array types must same.

int[] x={10,20,30};

int[] y;

y=x;

Accessing array elements:

int[] a=new int[5];

a[5]=60 it leads RTE, "Array Index Out Of Bound Exception".

a[4.0]=50;

If you are accessing array element with unmatched data type then it gives compile time exception, "Incorrect Syntax".

a[-4]=50 ; it leads RTE,"Array Index Out Of Bound Exception".

a[2.5] =50; it leads CTE, "Possible Loss of precision"

Either Float/Double/Long data type indexes should not use to accessing the array elements,violation leads to compile time exception.

Array element assignment is possible , when the class object is the subtype of element type.That means if an array is declared as object reference array ,we are allowed to assign the objects of either declared type or it's child classes.


ex 1: Number[] a = new Integer[5]; // Length 10, element type Integer

Double f = new Double(3.14); // Type Double, class Double

Integer i = new Integer(115); // Integer, class Integer

Number n = i; // Type Number, class Integer

a[0] = i; // OK, Integer is subtype of Integer

a[1] = n; // OK, Integer is subtype of Integer

a[2] = f; // No, Double not subtype of Integer

The above program successfully compile,but at run time a[2] =f throws "Array Store Exception", because the class of the object bound to f is not a subtype of a's element type (that is, Integer).

ex 2: String[] s = new String[5];

s[0] = "A"; it is OK

s[1]= new Integer[12]; CTE

Integer is not a child class of String,but expected thing is String or child class of String class .

ex 3: Object ob = new Object[8];

ob[0] = "X";

ob[1]= new Thread();

ob[2] = new Exception();

ob[3] = new Number();

ob[4] = new Integer(15);

the above program compile and run successfully, because all are subclasses of declared array type.
How do we Assignment of Array variables :

In general, we are allowed to place int variable in the place of double variable, because implicitly int will be promoted to double.but it is not possible to place int array in the place of double array. Like this , a character element can be assigned in the place of int element.But the char array can't be assigned in the place of int array.It gives compile time exception.


example : int[] a= {1,3,6,8};

char[] c={'a','b','c','d','e'};

int[] b = c; CTE, Incompatible Type


In the case of Object arrays ,we are allowed to place child class arrays in the place of parent class array.

example 1: wheels[] w= new wheels[8];
CLASSES AND OBJECTS IN JAVA

JAVA PROGRAMMING ENVIRONMENT

JAVA EXECUTION

JAVA CONSTRUCTORS

FIELD DECLARATIONS IN CLASS OF JAVA

EXCEPTIONS IN JAVA

EXCEPTIONS IN JAVA PART TWO

VARIABLE PARAMETERS IN JAVA

COMMENTS TYPES AND VARIABLES

JAVA JDBC AND ODBC

INTERFACE IN JAVA

OPERATORS IN JAVA



Threads in Java

Threads and Concurrent Execution:

In which expressions are evaluated and statements are executed one after the other: that is onsidered only a single thread of execution, where a thread is an independent sequential activity. A Java program may execute several threads concurrently, that is, potentially overlapping in time. For instance, one part of a program may continue computing while another part is blocked waiting for input.

Multiple Threads:

The main program creates a new thread, binds it to u, and starts it. Now two threads are executing concurrently: one executes main, and another executes run. While the main method is blocked waiting for keyboard input, the new thread keeps incrementing i. The new thread executes yield() to make sure that the other thread is allowed to run (when not blocked).

class Incrementer extends Thread {
public int i;

public void run() {

for (;;) { // Forever
i++; // increment i
yield();
}
}
}
class ThreadDemo {
public static void main(String[] args) throws IOException {

Incrementer u = new Incrementer();
u.start();
System.out.println("Repeatedly press Enter to get the current value of i:");
for (;;) {
System.in.read(); // Wait for keyboard input
System.out.println(u.i);
}
}
}

A thread is created and controlled using an object of the Thread class found in the package java.lang. A thread executes the method public void run () in an object of a class implementing the Runnable interface, also found in package java.lang. To every thread (independent sequential activity) there is a unique controlling Thread object, so the two are often thought of as being
identical.

One way to create and run a thread is to declare a class U as a subclass of Thread, overwriting its (trivial) run method. Then create an object u of class U and call u.start(). This will enable the thread to execute u.run() concurrently with other threads .

Alternatively, declare a class C that implements Runnable, create an object o of that class, create a thread object u = new Thread(o), and execute u.start (). This will enable the thread to
execute o.run() concurrently with other threads. Threads can communicate with each other via shared state, namely, by using and assigning static fields, non static fields, array elements, and pipes . By the design of Java, threads cannot use local variables and method parameters for communication.

RELATED POST:

EXCEPTIONS IN JAVA

Interfaces in Java

Interface Declarations in Java:
An interface describes fields and methods but does not implement them. An interface-
declaration may contain field descriptions, method descriptions, class declarations, and interface declarations, in any order.

interface-modifiers interface I extends-clause {
field-descriptions
method-descriptions
class-declarations
interface-declarations
}

An interface may be declared at top level or inside a class or interface but not inside a method or
constructor or initializer. At top level, the interface-modifiers may be public or absent. A public
interface is accessible also outside its package. Inside a class or interface, the interface-modifiers may be static (always implicitly understood) and at most one of public, protected, or private.

The extends-clause may be absent or have the form

extends I1, I2, ...

where I1, I2, ... is a nonempty list of interface names. If the extends-clause is present, then interface I describes all those members described by I1, I2,.., and interface I is a sub interface (and hence subtype) of I1, I2,.... Interface I can describe additional fields and methods but cannot override inherited members.

A field-description in an interface declares a named constant and must have the form
field-desc-modifiers type f = initializer;

where field-desc-modifiers is a list o f static, final, and public, none of which needs to be given
explicitly, as all are implicitly understood. The field initializer must be an expression involving only literals and operators, and static members of classes and interfaces.

A method-description for method m must have the form
method-desc-modifiers return-type m (formal-list) throws-clause;

where method-desc-modifiers is a list of abstract and public, both of which are understood and
need not be given explicitly.A class-declaration inside an interface is always implicitly static and public.

Classes Implementing Interfaces:
A class C may be declared to implement one or more interfaces by an implements-clause:

class C implements I1, I2, ...
class-body

In this case, C is a subtype I1, I2, and so on, and C must declare all the methods described by I1, I2,... with exactly the prescribed signatures and return types. A class may implement any number of interfaces. Fields, classes, and interfaces declared in I1, I2,... can be used in class C.

Three Interface Declarations:
The Colored interface describes method getColor, interface Drawable describes method draw, and Colored-Drawable describes both. The methods are implicitly public.

import java.awt.*;

interface Colored1 { Color getColor(); }

interface Drawable1 { void draw(Graphics g); }

interface ColoredDrawable extends Colored, Drawable {}


Classes Implementing Interfaces:
The methods getColor and draw must be public as in the interface declarations .

Ex1: class ColoredPaint extends Point implements Colored {
Color c;
ColoredPaint(int x, int y, Color c) {
super(x, y); this.c = c;
}

public Color getColor() {
return c;
}
}


Ex2: class ColoredDrawablePaint extends ColoredPaint implements ColoredDrawable {
Color c;

ColoredDrawablePaint(int x, int y, Color c) {
super(x, y, c);
}

public void draw(Graphics g) {
g.fillRect(x, y, 1, 1);
}
}


Ex3: class ColoredRectangle implements ColoredDrawable {

int x1, x2, y1, y2; // (x1, y1) upper left, (x2, y2) lower right corner
Color c;

ColoredRectangle(int x1, int y1, int x2, int y2, Color c){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.c = c; }

public Color getColor() {
return c;
}

public void draw(Graphics g) {
g.drawRect(x1, y1, x2-x1, y2-y1;
}
}

RELATED POST:

STATEMENTS IN JAVA

The Java Programming Environment

Installation and Development:

• Installing the Java Software Development Kit
• Development Environments

Now you will learn how to install the Java Software Development Kit (SDK) and how to compile and run various types of programs: console programs, graphical applications, and applets. You run the SDK tools by typing commands in a shell window. However, many programmers prefer the comfort of an integrated development environment. We show you how to use the freely available Forte environment to compile and run Java programs. There are many other environments for developing Java applications with similar user interfaces.

While easier to learn and use, integrated development environments take a long time to load and require heavy resources. As a middle ground, you may want to use a text editor that can call the Java compiler and interpreter. We show you a couple of text editors with Java integration.


Installing the Java Software Development Kit:

The most complete versions of Java are available for Sun's Solaris 2.x, Windows NT/2000, or Windows 95/98. Versions of Java in various states of development exist forLinux, OS/2, Macintosh, Windows 3.1, and many other platforms. Installation directions differ on each platform.Only the installation and compilation instructions for Java are system dependent. System independence is a major benefit of Java.

On Windows, simply run the self-installing executable file. On Solaris, look inside the compressed tar file for a README file. For other platforms, you'll need to consult the platform-specific installation instructions.

The setup procedure offers a default for the installation directory that contains the Java SDK version number, such as jdk1.2.3. If you prefer,you can change the installation directory to jdk. However, if you are a Java enthusiast who enjoys collecting different versions of the Java SDK, go ahead and accept the default.

For example, when we refer to the jdk/bin directory, we mean the directory named bin under the Java SDK installation directory. Under Windows, you'll have to use backslashes and drive letters such as c:\jdk\bin.

Setting the Execution Path:

After you are done installing the Java SDK, you need to carry out one additional step: add the jdk/bin directory to the execution path, the list of directories that the operating system traverses to locate executable files. Directions for this step also vary among operating systems.


Under Windows NT/2000, start the control panel, select System, then Environment.Scroll through the User Variables window until you find a variable named PATH. Add the jdk\bin directory to the beginning of the path, using a semicolon to separate the new entry, like this:
c:\jdk\bin;other stuff

Save your settings. Any new console windows that you start have the correct path.Here is how you test whether you did it right:Start a shell window. How you do this depends on your operating system. Type the line java -version and press the enter key. You should get a display such as this one: java version "1.3.0"

Java(TM) 2 Runtime Environment, Standard Edition
Java HotSpot(TM) Client VM

If instead you get a message such as “java: command not found,” “Bad command or filename,” or “The name specified is not recognized as an internal or external command, operable program or batch file,” then you need to go back and double-check your installation.


Installing the Library Source and Documentation in Java:

The library source files are delivered in the Java SDK as a compressed file src.jar , and you must unpack that file to get access to the source code. We highly recommend that you do that.

Simply do the following:

1. Make sure the Java SDK is installed and the jdk/bin directory is on the execution path.

2. Open a command shell.
3. Change to the jdk directory (e.g. /usr/local/jdk or C:\jdk).
4. Execute the command: jar xvf src.jar

The src.jar file contains the source code for all public libraries.

If you decide to use jar, follow these steps:


1. Make sure the Java SDK is installed and the jdk/bin directory is on the execution path.

2. Copy the documentation zip file into the directory that contains the jdk directory(such as /usr/local or C:\). The file is called jdkversion-doc.zip, whereversion is something like 1_2_3.
3. Open a command shell.
4. Change to the directory that contains the jdk directory and the compressed documentation file.
5. Execute the command: jar xvf jdkversion-doc.zip
where version is the appropriate version number.

RELATED POST

JAVA OPERATORS

Variables, Parameters, Fields, and Scope

variable : variable is declared inside a method, constructor, initializer block, or block statement. The variable can be used only in that block statement (or method or constructor or initializer block), and only after its declaration.

parameter: parameter is a special kind of variable: it is declared in the parameter list of a method or constructor,and is given a value when the method or constructor is called. The parameter can be used only in that method or constructor, and only after its declaration.

field:A field is declared inside a class, but not inside a method or constructor or initializer block of the class. It can be used anywhere in the class, also textually before its declaration.

Variable Declarations:

The purpose of a variable is to hold a value during the execution of a block statement (or method or constructor or initializer block). A variable-declaration has one of the forms
variable-modifier type varname1, varname2, ... ;
variable-modifier type varname1 = initializer1, ... ;

A variable-modifier may be final or absent. If a variable is declared final, then it must be initialized or assigned at most once at run-time (exactly once if it is ever used): it is a named constant. However, if the variable has reference type, then the object or array pointed to by the variable may still be modified. A variable initializer may be an expression or an array initializer .

Execution of the variable declaration will reserve space for the variable, then evaluate the initializer, if any, and store the resulting value in the variable. Unlike a field, a variable is not given a default value when declared, but the compiler checks that it has been given a value before it is used.

Scope of Variables, Parameters, and Fields:

The scope of a name is that part of the program in which the name is visible. The scope of a variable extends from just after its declaration to the end of the innermost enclosing block statement. The scope of a method or constructor parameter is the entire method or constructor body. For a control variable x declared in a for statement
for (int x = ...; ...; ...) body

the scope is the entire for statement, including the header and the body.

Within the scope of a variable or parameter x, one cannot redeclare x. However, one may declare a variable x within the scope of a field x, thus shadowing the field. Hence the scope of a field x is the entire class, except where shadowed by a variable or parameter of the same name, and except for initializers preceding the field's declaration

related post
comments and types in java

Comments ,Types,Variables and Scope

Comments and Program Layout:

Comments have no effect on the execution of the program but may be inserted anywhere to help
humans understand the program. There are two forms: one-line comments and delimited comments.Program layout has no effect on the computer's execution of the program but is used to help humans understand the structure of the program.

within the class we write like this:
// This is a one-line comment; it extends to the end of the line.

/* This is a delimited comment,
extending over several lines.
*/

int /* This delimited comment extends over part of a line */ x = 117;

Types:

A type is a set of values and operations on them. A type is either a primitive type or a reference type.

Primitive Types :


A primitive type is either boolean or one of the numeric types char, byte, short, int, long, float,
and double.

The integer types are exact within their range. They use signed 2's complement representation (except for char), so when the most positive number in a type is max, then the most negative number is -max-1. The floating-point types are inexact and follow IEEE754, with the number of significant digits indicated by "sigdig." For character escape sequences such as \u0000.
Integer literals (of type byte, char, short, int, or long) may be written in three different bases:

Notation Base Distinction

Decimal 10 no leading 0

Hexa Decimal 16 leading 0x

octal 8 leading 0

For all primitive types there are corresponding wrapper classes , namely Boolean and Character as well as Byte, Short, Integer, Long, Float, and Double, where the last six have the common superclass Number. To use a primitive value, such as 17, where an object is expected, use an object of its wrapper class, such as new Integer(17).

Reference Types :

A reference type is either a class type defined by a class declaration , or an interface type defined by an interface declaration , or an array type .A value of reference type is either null or a reference to an object or array. The special value null denotes "no object." The literal null, denoting the null value, can have any reference type.

Array Types :

An array type has the form t[], where t is any type. An array type t[] is a reference type. Hence a value of array type t[] is either null, or is a reference to an array whose element type is precisely t (when t is a primitive type), or is a subtype of t (when t is a reference type).

Subtypes and Compatibility :

A type t1 may be a subtype of a type t2, in which case t2 is a supertype of t1. Intuitively this means that any value v1 of type t1 can be used where a value of type t2 is expected. When t1 and t2 are reference types, t1 must provide at least the functionality (methods and fields) provided by t2. In particular, any value v1 of type t1 may be bound to a variable or field or parameter x2 of type t2, e.g., by the assignment x2 = v1 or by parameter passing. We also say that types t1 and t2 are compatible.

The following rules determine when a type t1 is a subtype of a type t2:

Every type is a subtype of itself.

If t1 is a subtype of t2, and t2 is a subtype of t3, then t1 is a subtype of t3.

char is a subtype of int, long, float, and double.

byte is a subtype of short, int, long, float, and double.

short is a subtype of int, long, float, and double.

int is a subtype of long, float, and double.

long is a subtype of float and double.

float is a subtype of double.

If t1 and t2 are classes, then t1 is a subtype of t2 if t1 is a subclass of t2.

If t1 and t2 are interfaces, then t1 is a subtype of t2 if t1 is a sub interface of t2.

If t1 is a class and t2 is an interface, then t1 is a subtype of t2 provided that t1 (is a
subclass of a class that) implements t2 or implements a subinterface of t2.

Array type t1 [] is a subtype of array type t2 [] if reference type t1 is a subtype of
reference type t2.

reference type t, including any array type, is also a subtype of predefined class Object.

No primitive type is a subtype of a reference type. No reference type is a subtype of a primitive type.

RELATED POST

RUNNING JAVA

Running Java

Compilation, Loading, and Execution :

Before a Java program can be executed, it must be compiled and loaded. The compiler checks that the Java program is legal: that the program conforms to the Java syntax , that operators are applied operands of the correct type, and so on. If so, the compiler generates so-called class files. Execution then starts by loading the needed class files.

Thus running a Java program involves three stages:
compilation : checks that the program is well-formed .
loading : loads and initializes classes.
execution :runs the program code.

To run a compiled program, the Java interpreter always starts execution with the code in
the main method in the class you indicate. Thus, you must have a main method in the source
file for your class in order for your code to execute. You can, of course, add your own
methods to a class and call them from the main method.

Language Fundamentals:
A name in a Java program is called an identifier , which can be used for representing classes,methods,variables and labels.
If a name is composed of several words, then each word (except possibly the first one)
begins with an uppercase letter.
Names of variables, fields, and methods begin with a lowercase letter.
Ex: vehicle,total_number.
Names of classes and interfaces begin with an uppercase letter. Examples: Cube.
Named constants (that is, final variables and fields) are written entirely in uppercase, and
the parts of composite names are separated by underscores (_).
Exs: CENTER,MAX_VALUE.
Package names are sequences of dot-separated lowercase names.
No identifier starts with the digits.
There is no length limit for Java identifier ,but SUN highly recommended upto 15 char's for the identifier.identifiers in Java are case sensitive.
we are nor allowed reserved words as identifiers.

A legal name (of a variable, method, field, parameter, class, interface or package) starts with a letter ordollar sign ($) or underscore (_), and continues with zero or more letters or dollar signs or underscoresor digits (0–9). Avoid dollar signs in class names. Uppercase letters and lowercase letters are considered distinct.

Reserved words:

some identifiers are reserved in Java,which has separate functionality and meaning ,such type of reserved identifiers are called reserved words.53 reserved words are there in Java.

keywords for Primitive Data Types:8
Four of them are integer types; two are floating-point
number types; one is the character type char, used for characters in the Unicode encoding, and one is a boolean type for truth values.

Data Type size range wrapper class Default

byte 1byte -128 to +127 Byte 0

short 2bytes -32768 to +32767 Short 0

int 4bytes -2147483648 to Integer 0
2147483647

float 4bytes -3.4e38 to 3.4e38 Float 0.0

long 8bytes -9,223,372,036,854,775,808L Long 0
to 9,223,372,036,854,775,807L

double 8bytes -1.7e308 to 1.7e308 Double 0.0

char 2bytes 0 to 65535 Character 0 (empty
space)

boolean not not applicable Boolean false
applicable



keywords for flow control:

  • if
  • else
  • default
  • switch
  • case
  • break
  • continue
  • do
  • while]
  • return
  • for
keywords for Exception Handling :5

  • try
  • catch
  • finally
  • throw
  • throws
keywords for Modifiers :11

  • public
  • private
  • protected
  • static
  • final
  • abstract
  • transient
  • volatile
  • native
  • synchronized
  • strict fp
keywords for class:6

  • class
  • interface
  • implements
  • extends
  • import
  • package
Object related keywords:4
  • new
  • instance of
  • super
  • this
return type keyword :1
  • void -indicates no return type
unused keywords:
  • const -use final
  • goto
New keyword in j2se1.5 :

  • enum -(enumeration) for defining list of named constants.
  • all keywords contain only lower case letters,symbols.