El-Shorouk Academy Acad. Year: 2010 / 2011

Higher Institute for Computer & Term : 1st

Information Technology Year : 3rd

Computer Science Department Professor:Mohammed Zeweedy

Advanced Programming Using (Java)

Section (1)

Section Contents:

-Overview of The NetBeans IDE

-C# Vs. Java

-Java Syntax

-Sample Programs

Overview of the NetBeans IDE:

Setting up the Project

To create an IDE project:

  1. Start NetBeans IDE.
  2. In the IDE, choose File > New Project (Ctrl-Shift-N), as shown in the figure below.
  1. In the New Project wizard, expand the Java category and select Java Application as shown in the figure below. Then click Next.

  1. In the Name and Location page of the wizard, do the following (as shown in the figure below):
  2. In the Project Name field, typeHelloWorldApp.
  3. Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
  4. In the Create Main Class field, typehelloworldapp.HelloWorldApp.
  5. Leave the Set as Main Project checkbox selected.

  1. Click Finish.

The project is created and opened in the IDE. You should see the following components:

  • The Projects window, which contains a tree view of the components of the project, including source files, libraries that your code depends on, and so on.
  • The Source Editor window with a file calledHelloWorldAppopen.
  • The Navigator window, which you can use to quickly navigate between elements within the selected class.
  • The Tasks window, which lists compilation errors as well other tasks that are marked with keywords such as XXX and TODO.

Adding Code to the Generated Source File

Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE has created a skeleton main class for you. You can add the "Hello World!" message to the skeleton code by replacing the line:

// TODO code application logic here

with the line:

System.out.println("Hello World!");

Save the change by choosing File > Save.

The file should look something like the following code sample.

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

packagehelloworldapp;

/**

*

* @author <your name>

*/

public class HelloWorldApp {

/**

* @paramargs the command line arguments

*/

public static void main(String[] args) {

System.out.println("Hello World!");

}

}

Compiling and Running the Program

Because of the IDE's Compile on Save feature, you do not have to manually compile your project in order to run it in the IDE. When you save a Java source file, the IDE automatically compiles it.

The Compile on Save feature can be turned off in the Project Properties window. Right-click your project, select Properties. In the Properties window, choose the Compiling tab. The Compile on Save checkbox is right at the top. Note that in the Project Properties window you can configure numerous settings for your project: project libraries, packaging, building, running, etc.

To run the program:

  • Choose Run > Run Main Project (F6).

The next figure shows what you should now see.

Congratulations! Your program works!

If there are compilation errors, they are marked with red glyphs in the left and right margins of the Source Editor. The glyphs in the left margin indicate errors for the corresponding lines. The glyphs in the right margin show all of the areas of the file that have errors, including errors in lines that are not visible. You can mouse over an error mark to get a description of the error. You can click a glyph in the right margin to jump to the line with the error.

Building and Deploying the Application

Once you have written and test run your application, you can use the Clean and Build command to build your application for deployment. When you use the Clean and Build command, the IDE runs a build script that performs the following tasks:

  • Deletes any previously compiled files and other build outputs.
  • Recompiles the application and builds a JAR file containing the compiled files.

To build your application:

  • Choose Run > Clean and Build Main Project (Shift-F11)

You can view the build outputs by opening the Files window and expanding theHelloWorldAppnode. The compiled bytecode fileHelloWorldApp.classis within thebuild/classes/helloworldappsubnode. A deployable JAR file that contains theHelloWorldApp.classis within thedistnode.

C# vs. Java:

C# and Java are both new-generation languages descended from a line including C and C++. Each includes advanced features, like garbage collection, which remove some of the low level maintenance tasks from the programmer. In a lot of areas they are syntactically similar.

Both C# and Java compile initially to an intermediate language: C# to Microsoft Intermediate Language (MSIL), and Java to Java bytecode. In each case the intermediate language can be run - by interpretation or just-in-time compilation - on an appropriate 'virtual machine'. In C#, however, more support is given for the further compilation of the intermediate language code into native code.

C# contains more primitive data types than Java and also allows more extension to the value types. For example, C# supports 'enumerations', type-safe value types which are limited to a defined set of constant variables and 'structs', which are user-defined value types

Unlike Java, C# has the useful feature that we can overload various operators.

Like Java, C# gives up on multiple class inheritance in favour of a single inheritance model extended by the multiple inheritance of interface. However, polymorphism is handled in a more complicated fashion, with derived class methods either 'overriding' or 'hiding' super class methods

C# also uses 'delegates' - type-safe method pointers. These are used to implement event-handling.

In Java, multi-dimensional arrays are implemented solely with single-dimensional arrays (where arrays can be members of other arrays. In addition to jagged arrays, however, C# also implements genuine rectangular array.

Below is a list of features C# and Java share, which are intended to improve on C++, but it is very important to be aware of the similarities.

  • Compiles into machine-independent language-independent code which runs in a managed execution environment.
  • Garbage Collection coupled with the elimination of pointers (in C# restricted use is permitted within code marked unsafe)
  • Powerful reflection capabilities
  • No header files, all code scoped to packages or assemblies, no problems declaring one class before another with circular dependencies
  • Classes all descend from object and must be allocated on the heap with new keyword
  • Thread support by putting a lock on objects when entering code marked as locked/synchronized
  • Interfaces, with multiple-inheritance of interfaces, single inheritance of implementations
  • Inner classes
  • No concept of inheriting a class with a specified access level
  • No global functions or constants, everything belongs to a class
  • Arrays and strings with lengths built-in and bounds checking
  • The '.' operator is always used, no more ->, :: operators
  • null and boolean/bool are keywords
  • All values are initialized before use
  • Can't use integers to govern if statements.
  • Try Blocks can have a finally clause

Features of C# Absent in Java

  • C# includes more primitive types and the functionality to catch arithmetic exceptions.
  • Includes a large number of notational conveniences over Java, many of which, such as operator overloading and user-defined casts, are already familiar to the large community of C++ programmers.
  • Event handling is a "first class citizen"—it is part of the language itself.
  • Allows the definition of "structs", which are similar to classes but may be allocated on the stack (unlike instances of classes in C# and Java).
  • C# implements properties as part of the language syntax. .
  • C# allows anonymous methods providing closure functionality.
  • C# allows iterator that employs co-routines via a functional-style yield keyword.
  • C# has support for output parameters, aiding in the return of multiple values, a feature shared by C++ and SQL.
  • C# has the ability to alias namespaces.
  • C# has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate from its own class methods. This allows it also to implement two different interfaces which happen to have a method of the same name. The methods of an interface do not need to be public; they can be made to be accessible only via that interface.
  • C# provides integration with COM.
  • Following the example of C and C++, C# allows call by reference for primitive and reference types.

Features of Java Absent in C#

  • Java's strict keyword guarantees that the result of floating point operations remain the same across platforms.
  • Java supports checked exceptions for better enforcement of error trapping and handling.

Access Modifiers

JAVA

/

C#

public
Access not limited
protected
Access limited to the package or
subclass in a different package
(no access modifier)
Access limited to the package
private
Access limited to the containing type / Public
Access not limited
protected
Access limited to the containing class or
types derived from the containing class
protected internal
Access limited to this program or
types derived from the containing class
(no access modifier)
by default it is private
internal
Access limited to this program
private

Access limited to the containing type

Pass By Value vs. Pass By Reference

JAVA

/

C#

Primitive types are passed to methods by value (a copy is made),
while reference types are passed by reference.
Java cannot pass a primitive type as
a reference type. If you want to do so,
wrap the primitive type into a class. / Value types are passed to methods by value (a copy is made),
while reference types are passed by reference.
C# can pass a value type as
a reference type by marking it
with a ref keyword.
public void aMethod(ref int age, ref int ID){}
Note that you need to use the ref keyword in both
the method declaration and the actual call to the method.

aRef.aMethod(ref age, ref ID);

Types
JAVA / C#
type:
primitive types
reference types
numeric-type:
integral types
floating-point types
integral-type:
byte
short
int
long
char
floating-point-type:
float
double
reference-type:
class types
interface types
array types
Primitive types(8)
boolean
byte
char
short
int
long
float
double / type:
value types
reference types
numeric-type:
integral types
floating-point types
decimal
integral-type:
sbyte
byte
short
ushort
int
uint
long
ulong
char
floating-point-type:
float
double
reference-type:
class types
interface types
array types
delegate types
Predefined types or
system-provided types:
object
string
sbyte
short
int
long
byte
ushort
uint
ulong
float
double
bool
char
decimal
NOTE: value types include simple types,
enum types(derived from System.Enum)
andstruct types.
Converting a string to a number
JAVA / C#
String s = "123.45";
int i = new Double(s).intValue(); //123
int i2 = (int)new Double(s).doubleValue(); //123 / string s = "123.45";
int i = (int)s.ToSingle();// 123
int i2 = s.ToInt16(); // 123
String vs. string
String is a reference type but immutable.
for example,(Note: the Upper-calse S for String)
String s1 = "hello";
String s2 = s1;
s1 = "goodbye";
System.out.println(s2);//hello
System.out.println(s1);//goodbye
string path = "C:\\My Documents\\";
There is no verbatim string in Java / string is a reference type but immutable.
for example,(Note: the lower-case s for string)
string s1 = "hello";
string s2 = s1;
s1 = "goodbye";
System.Console.WriteLine(s2);//hello
System.Console.WriteLine(s1);//goodbye
string path = "C:\\My Documents\\";
can be written with verbatim string like:
string path = @"C:\My Documents\";
Primitives vs. Objects
JAVA / C#
Java primitives cannot be assigned to
reference types directly before Java 5.
class Test
{
public static void main(String[] args) {
int i = 123;
Object o = i; // error
int j = (int) o; // error
System.out.println(3.toString());//error
}
} / C# provides a "unified type system".
All types derive from the type object
class Test
{
static void Main() {
int i = 123;
object o = i; // boxing
int j = (int) o; // unboxing
Console.WriteLine(3.ToString());
}
}
Primitive Type vs. Value Type
Java has two types:
primitive types and
reference types
All classes including arrays and interfaces
are reference types.
There are only eight(8) primitive types:
boolean
byte
short
char
int
long
float
double / C# has two types:
value types and
reference types
All classes including delegate, arrays
and interfaces are reference types.
Value types include simple types, enum types
andstruct types(15).
sbyte
byte
short
ushort
int
uint
long
ulong
float
double
bool
char
decimal
enum
structs
Pointer
JAVA / C#
There is no pointer concept in Java
int i = 5;
int p;
p = i;
p = 10;
System.out.print(i);//5 / Using pointer in C# is not safe.
unsafe
{
int i = 5;
int *p;
p = &i;
*p = 10;
System.Console.Write(i);//10
}
Operators
{ } [ ] ( ) . , : ;
+ - * / % & | ^ ! ~
= > ? ++ -- & || >
== != <= >= += -= *= /= %= &=
|= ^= <= >= >
Java doesn't have operator ->
Pre-processing directives
None / { } [ ] ( ) . , : ;
+ - * / % & | ^ ! ~
= > ? ++ -- & || >
== != <= >= += -= *= /= %= &=
|= ^= <= >= ->
C# doesn't have operator >
Pre-processing directives
#
Objects
JAVA / C#
Everything derives from Object.
This includes classes you create,
not including primitive types. / Everything ultimately derives from Object.
This includes classes you create,
as well as value types such as int or structs.
new
JAVA / C#
With reference types, the new keyword instantiate objects on the heap.
You cannot use new to instantiate a primitive type. / With reference types, the new keyword instantiate objects on the heap,
but with value types such as structs, the object is created
on the stack and a constructor is called. You can, in fact,
create a struct on the stack without using new,
but you must initialize all the values in the struct by hand
before you use it (before you pass it to a method)
or it won't compile.
namespace vs. package
JAVA / C#
Packages are used to organize files or public types to avoid
type conflicts.
Package constructs can be mapped to a file system.
System.Security.Cryptography.AsymmetricAlgorithmaa;
may be replaced:
import System.Security.Crypography;
class xxx { ...
AsymmetricAlgorithmaa;
There is no alias for packages.
You have to use import statement
or fully-qualified name to
mention the specific type.
pacakge N1.N2;
class A {}
class B {}
or
package N1.N2;
class A {}
//another source file
package N1.N2;
class B {}
package cannot be nested.
One source file can only
have one package statement. / Namespaces are used to organize programs,
both as an "internal" organization system for a program,
and as an "external" organization system.
System.Security.Cryptography.AsymmetricAlgorithmaa;
may be replaced:
using System.Security.Crypography;
AsymmetricAlgorithmaa;
Alternatively, one could specify an alias
for the the namespace, eg
using myAlias = System.Security.Crypography;
and then refer to the class with
myAlias.AsymmetricAlgorithm
namespace N1.N2
{
class A {}
class B {}
}
or
namespace N1
{
namespace N2
{
class A {}
class B {}
}
}
Method Modifiers
JAVA / C#
public
protected
no modifier
private
static
final
abstract
native
synchronized
strictfp / public
protected
internal
private
static
sealed
abstract
extern
virtual
override
new
Maximums and Minimums
JAVA / C#
To get maximum and minimum values:
Byte.MAX_VALUE
Byte.MIN_VALUE
Short.MAX_VALUE
Short.MIN_VALUE
Integer.MAX_VALUE
Integer.MIN_VALUE
Long.MAX_VALUE
Long.MIN_VALUE
Float.MAX_VALUE
Float.MIN_VALUE
Double.MAX_VALUE
Double.MIN_VALUE / To get maximum and minimum values:
System.Byte.MaxValue
System.Byte.MinValue
System.Int16.MaxValue
System.Int16.MinValue
System.Int32.MaxValue
System.Int32.MinValue
System.Int64.MaxValue
System.Int64.MinValue
System.Single.MaxValue
System.Single.MinValue
System.Double.MaxValue
System.Double.MinValue
System.Decimal.MaxValue
System.Decimal.MinValue
Keywords & Reserved Words
JAVA / C#
52
abstract do if package synchronized
boolean double implements private this
break else import protected throw
byte extends instanceof public throws
case false int return transient
catch final interface short true
char finally long static try
class float native strictfp void
const for new super volatile
continue goto null switch while
default assert(1.4) enum(1.5)
C# doesn't have
assert boolean extends final implements
instanceof native package strictfp super
synchronized throws transient / 77
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreachgoto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeofstackalloc static string
struct switch this throw true
try typeofuintulong unchecked
unsafe ushort using virtual void
volatile while
Java doesn't have
as base bool checked decimal
delegate event explicit extern
fixed foreach implicit int internal
is lock namespace object operator
out override paramsreadonly ref
sbyte sealed sizeofstackalloc string
structtypeofuintulong unchecked
unsafe ushort using virtual
Common Escape Sequences
JAVA / C#
Character Escape Sequence
single quote \'
double quote \"
backslash \\
Backspace \b
Form feed \f
New Line \n
Carriage Return \r
Horizontal Tab \t
Unicode \u
hexadecimal \x / Character Escape Sequence
single quote \'
double quote \"
backslash \\
Alert \a
Backspace \b
Form feed \f
New Line \n
Carriage Return \r
Horizontal Tab \t
Vertical Tab \v
Unicode \u
hexidecimal \x
null \0 (zero)
Class Modifiers
JAVA / C#
for outer class
public
abstract
final
no modifier
for nested class
public
abstract
final
private
no modifier / for outer class
public
abstract
sealed
internal(default/no modifier)
for nested class
public
abstract
sealed
protected
internal
protected internal
private
new
Array Type
JAVA / C#
Java has two kinds of arrays:
  • single-dimensional
  • multi-dimensional or jagged arrays (arrays of arrays).
Note that the declaration has big difference from C#
int[] myIntArray = new int[5]; //create a single-dimensional array
int[] myIntArray = { 2, 4, 6, 8, 10 }; // initialize an array
int[,] myRectangularArray = new int[rows, columns]; //illegal
int[,] myRectangularArray =
{
{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11} //illegal
};
int [,,] array = new int [3, 4, 5];//illegal
int [1,1,1] = 5;//illegal
int [][][] array = new int [3][4][5]; // ok
int [1][1][1] = 5; //ok
class Test
{
public static void main(String[] args) {
int[] a1; // single-dimensional array of int
int[][] a2; // 2-dimensional array of int
int[][][] a3; // 3-dimensional array of int
int[][] j2; // "jagged" array: array of (array of int)
int[][][] j3; // array of (array of (array of int))
}
}
class Test
{
public static void main(String[] args) {
int[] a1 = new int[] {1, 2, 3};
int[][] a2 = new int[][] {{1, 2, 3}, {4, 5, 6}};
int[][][] a3 = new int[10][20][30];
int[][] j2 = new int[3][];
j2[0] = new int[] {1, 2, 3};
j2[1] = new int[] {1, 2, 3, 4, 5, 6};
j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
}
}
class Test
{
public static void main(String[] args) {
int[] arr = new int[5];
for (int i = 0; i <arr.length; i++)
arr[i] = i * i;
for (int i = 0; i <arr.length; i++)
System.out.println("arr[" + i + "] = " + arr[i]);
}
}
int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new int[] {5, 6, 7, 8, 9, 10}};
//access elements
for (int i = 0; i <jag.length; i++)
for (int j = 0; j < jag[i].length; j++)
System.out.println(jag[i][j]); / C# has three kinds of arrays:
  • single-dimensional
  • multi-dimensional rectangular arrays
  • jagged arrays (arrays of arrays).
Note that the declaration has big difference from Java
int[] myIntArray = new int[5]; //create a single-dimensional array
int[] myIntArray = { 2, 4, 6, 8, 10 }; // initialize an array
int[,] myRectangularArray = new int[rows, columns]; //create a rectangular array
int[,] myRectangularArray =
{
{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11} //intialize array
};
int [,,] array = new int [3, 4, 5]; // creates a 3x4x5 array
int [1,1,1] = 5;
int [][][] array = new int [3][4][5]; // creates 1+3+12=16 arrays
int [1][1][1] = 5;
class Test
{
static void Main() {
int[] a1; // single-dimensional array of int
int[,] a2; // 2-dimensional array of int
int[,,] a3; // 3-dimensional array of int
int[][] j2; // "jagged" array: array of (array of int)
int[][][] j3; // array of (array of (array of int))
}
}
class Test
{
static void Main() {
int[] a1 = new int[] {1, 2, 3};
int[,] a2 = new int[,] {{1, 2, 3}, {4, 5, 6}};
int[,,] a3 = new int[10, 20, 30];
int[][] j2 = new int[3][];
j2[0] = new int[] {1, 2, 3};
j2[1] = new int[] {1, 2, 3, 4, 5, 6};
j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
}
}
class Test
{
static void Main() {
int[] arr = new int[5];
for (int i = 0; i <arr.Length; i++)
arr[i] = i * i;
for (int i = 0; i <arr.Length; i++)
Console.WriteLine("arr[{0}] = {1}", i, arr[i]);
}
}
int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new int[] {5, 6, 7, 8, 9, 10}};
for (int i = 0; i <jag.Length; i++)
for (int j = 0; j < jag[i].Length; j++)
System.Console.WriteLine(jag[i][j]);
or
for (int i = 0; i <jag.GetLength(0); i++)
for (int j = 0; j < jag[i].GetLength(0); j++)
System.Console.WriteLine(jag[i][j]);

Application Startup