Sunday, 26 May 2013

Arrays, References, Memory Leaks


                      Arrays are references! 
                      Garbage collection reclaims arrays that can not be accessed! 
                      References are initialized to null 
                      When done with a reference set it to null 

public classArrayExamples{public static void main( String args[] )
{int[] integerArray = new int[ 4 ];integerArray[ 1 ] = 12integerArray = new int[ 2 ]; // Memory Leak - No!integerArray[  1  ]  =  5;int[] aliasForArray = integerArray;aliasForArray[  1  ]  =  10;System.out.println( integerArray[ 1 ] ); //Prints 10}
}
HEAP ALLOCATION
integerArray[ 1 ] = 12
integerArray = new int[ 2 ]; // Memory Leak - No!
integerArray[  1  ]  =  5;
int[] aliasForArray = integerArray;
aliasForArray[  1  ]  =  10;
Memory Problems in C/C++
Memory Leaks
Memory that program has allocated but can no longer access  int* trouble = new int( 5 );

Arrays


Major differences with C/C++ arrays:
Java arrays are references
Java arrays know their size
Java checks the bounds of an array when accessed
Java multidimensional arrays need not be rectangular
Java array elements are initialized

Example 1:)
public class SimpleReferenceExample{public static void main( String args[] )
{// Reference allocated, no array space allocatedfloat[] sampleArray;//allocate array locations on heapsampleArray = new float[ 12 ];// Indexing starts at 0 like C/C++sampleArray[ 0 ] = 3.2F;int[] integerArray = new int[ 3 ];
// Reference refers to new array.// Old array available for garbage collectionsampleArray = new float[ 2 ];}
} Example 2:)
public class ArrayExamples{public static void main( String args[] )
{// Two locations to place [ ]int integerArray[ ];int[ ] alias;integerArray = new int[ 10 ]; // Indexed from 0 to 9// Note use of .length to get array sizefor ( int index = 0; index < integerArray.length; index++ )
integerArray[  index  ]  =  5;alias = integerArray; // Arrays are referencesalias[  3  ]  =  10;System.out.println( integerArray[ 3 ] ); //Prints 10
integerArray = new int[ 8 ];System.out.println( integerArray[ 3 ] ); //Prints 0, Why?System.out.println( alias[ 3 ] ); //Prints 10System.out.println( integerArray ); //Prints [I@5e300868}}

Casting


class Casting{public static void main( String args[] )
{int anInt = 5;float aFloat = 5.8f;aFloat = anInt; // Implicit casts up are okanInt = aFloat ; // Compile error,
// must explicitly cast downanInt = (int) aFloat ;float error = 5.8; // Compile error, 5.8 is doublefloat works = ( float) 5.8;char c = (char) aFloat;double aDouble = 12D;double bDouble = anInt + aDouble; // anInt is cast upto double,int noWay = 5 / 0; // Compile error, compiler detects
// zero divideint zero = 0;int trouble = 5 / zero; //Some compilers may give error hereint notZeroYet;notZeroYet = 0;
 trouble = 5 / notZeroYet ; // No compile error!}}
Ints and Booleans are Different
class UseBoolean {public static void main( String args[] )
{if ( ( 5 > 4 ) == true )System.out.println( "Java's explicit compare " );if ( 5 > 4 )System.out.println( "Java's implicit compare " );if ( ( 5 > 4 ) != 0 ) // Compile errorSystem.out.println( "C way does not work" );boolean cantCastFromIntToBoolean = (boolean) 0;
// compile errorint  x  =  10;int  y  =  5;if ( x = y ) // Compile error

System.out.println( "This does not work in Java " );}} 

Basic Data Types


class PrimitiveTypes{public static void main( String args[] )
{// Integral Typesbyte aByteVariable; // 8-bitsshort aShortVariable; // 16-bitsint aIntVariable; // 32-bitslong aLongVariable; // 64-bits// Floating-Point Typesfloat aFloatVariable; // 32-bit IEEE 754 floatdouble aDoubleVariable; // 64-bit IEEE 754 float// Character Typechar aCharVariable; // always 16-bit Unicode// Boolean Typesboolean aBooleanVariable; // true or false}}
Operations on Primitive Types

class Operations{public static void main( String args[] )
{int a = 2;int b = +4;int c = a + b;if ( b > a )
System.out.println("b is larger");else
System.out.println("a is larger");System.out.println( a << 1); // Shift left: 4System.out.println( a >> 1); // Shift right: 1System.out.println( ~a ); // bitwise negation: -3System.out.println( a | b); // bitwise OR: 6System.out.println( a ^ b); // bitwise XOR: 6System.out.println( a & b); // bit

Guide to JAVA

CLASSPATH
Java uses the environment variable CLASSPATH to locate class libraries
• .class files those needed to compile or run the program it searches from
CLASSPATH
By default class path consists only the current directory but you can provide them in –classpath option of javac or include directories in CLASSPATH environment variables.
Example classpath = . ; c:\java\lib; c:\csi211\lab


Some Basic Java Syntax
Java Comments
/* Standard C comment works  */
// C++ comment works
/** Special comment for documentation – java comments */
class Syntax
{ public static void main( String args[] ){
int aVariable = 5;double aFloat = 5.8;
if ( aVariable < aFloat )System.out.println( "True" );
int b = 10; // This is legal in Javachar c;c = 'a';
}}
Java Program Style and Layout
Three different indentation styles you can use
You can pick a reasonable indentation style and use it consistently in your programs

Style#1
class Syntax { // brace starts from here
public static void main( String args[] ) {int aVariable = 5;if ( aVariable < aFloat )
System.out.println( "True" );}}
Style #2
class Syntax
{ // brace startspublic static void main( String args[] ){
int aVariable = 5;if ( aVariable < aFloat )System.out.println( "True" );}}
Style#3
class Syntax{// brace startspublic static void main( String args[] )
{int aVariable = 5;if ( aVariable < aFloat )
System.out.println( "True" );}}
Naming conventions
Class Naming Uses Capitalized word(s) i.e. Title case
Examples:-   HelloWorld, MyList, StudentMark
Wrong: helloWorld,  HW (do not use abbreviat

An Example HelloWorld


/**    This is my first java program */
public class HelloWorldExample
{ public static void main( String args[] ){
System.out.println("Hello World");}}

Java Source Code Naming Conventions
All java source file should end in .java
Each .java file can contain only one public class
The name of the file should be the name of the public class plus ".java"
Do not use abbreviations in the name of the class
If the class name contains multiple words then capitalize the first letter of each word ex. HelloWorld.java

Java - The Platform


Java has a large API (application programming interface) covering a wide range of areas The following list of Java APIs and applications from Sun show the range of applications of Java . For reference http://java.sun.com/products/index.html
Java Foundation Classes (JFC) - GUI
JDBC Database Access
JavaBeans - componentware
Java Web Server
EmbeddedJava - Java on embedded devices


JAVA IDE
Using JDK you can compile and run java program from command line.
 javac HelloWorld. java  - compiling here and it will produce HelloWorld.class i.e. bytecode.
java HelloWorld  - It runs java byte code on native machine
Creating, Compiling, Debugging and Execution for these four steps JDK is not user friendly. IDE is provided for that. A list of IDEs are:
 Eclipse  - from IBM
 Netbeans.

United International University Course Outline

Trimester: Spring 2013
Course: CSI 211
Course Title: Object-oriented Programming
Faculty: Md. Faisal Kabir
Email: faisal@cse.uiu.ac.bd
Assessment:
Component Marks(%)
Attendance 5
Continuous Assessment - Class test 10
Continuous Assessment - Assignment 15
Midterm Examination 30
Final Examination 40
Total 100
Reference Book
• The Complete Reference Herbert Schieldt Java 2.0
• The Java Programming, Deitel and Deitel
This document is prepared by : Dr. S M Monzurur Rahman, Professor, dept. of CSE,UIU
Week 1
Lecture 1
Fundamental of Programming; Java Introduction; Basic Java Syntax: IO
Basic Data Types, Primitive Type Ranges, Operations on Primitive Types, NaN
and Infinity, Casting Default Values of Variables.
Lecture 2
Arrays; Multidimensional Arrays; Some JDK Array Features; Strings: Strings are
Constant!, Strings Reading Command Line Arguments; Control Structures; Jump
Statements; Methods (Functions); Final Variables.
Week 2
Lecture 1
Classes: Fields, Methods; Initializing Fields; Direct Assignment; Instance
Initialization Blocks; Constructors; Overloading Methods; this ;Finalize; Access
Levels for Fields and Methods; Class Names, Packages, Import, CLASSPATH.
Lecture 2
Class members; variables References ; Static, recursion.
• Class Test -1
2
Week 3
Lecture 1
Object oriented concept, Information hiding; examples.
Lecture 2
Inheritance; Class Object; Inheritance and Name Clashes; Super; Constructors
and Inheritance; Static Methods; Access Levels and Inheritance; Inheritance and
Final; Abstract Classes; Relationships between Classes: Is-kind-of, is-a, is-a-typeof
is-analogous-to is-part-of or has-a.
Week 4
Lecture 1
Class Test -2
Interfaces; Clone; Abstract method; Abstract method vs interfaces.
Lecture 2
Java collections.
Week 5
Lecture 1
Exceptions Handling; Java IO
Lecture 2
Nested and Inner Classes.
Week 6
Mid Exam
Week 7
Lecture 1
Threads;
Lecture 2
Generics
Week 8
Lecture 1
Problem Solving – Class Participation (no lecture notes)
Lecture 2
Serialization; Making an Object Serializable; Serializable objects can contain
other objects; Saving and Recovering; Non-Serializable Fields – transient;
Customizing Deserialization; Customizing Serialization; Class Versions; Serial
version.
3
Week 9
Lecture 1
Class Test -3
Internationalization;
Lecture 2
Java Foundation Classes, Java Graphics.
Week 10
Lecture 1
Layouts: Flow layout, Grid layout, border lay out card layout
Events, Event Handling, Containers.
Lecture 2
Class Participation (Problems will be given and solutions will be asked to students,
Class Test-4 equivalent)
Week 11
Lecture 1
GUI Components
Lecture 2
Applet;
Week 12
Lecture 1
More about applets
Lecture 2
Class Test -4
A variety of examples on Applets part1
Week 13
Lecture 1
Architecture Design Pattern; Model-View in Java.
Lecture 2
• Summarization
END OF SEMESTER!!! ENJOY!!!