Anda di halaman 1dari 38

mainly for c++ programmer

Why Java ?
Easy to learn [ Designed to be used on the Internet ]

JVM stands for

Java Virtual Machine

Unlike other languages, Java executables are executed on a CPU that does not exist.

Platform Dependent
myprog.c C source code myprog.exe


machine code


Platform Independent Java source code myprog.class




Some Keywords
native Indicates a method is written in a platform-dependent language, such as C. new Used to instantiate an object by invoking the constructor. static Makes a method or a variable belong to a class as opposed to an instance. final Makes it impossible to extend a class, override a method, or reinitialize a variable.

strictfp Used in front of a method or class to indicate that floating-point numbers will follow FP-strict rules in all expressions. synchronized Indicates that a method can be accessed by only one thread at a time. transient Prevents fields from ever being serialized. Transient fields are always skipped when objects are serialized. volatile Indicates a variable may change out of sync because it is used in threads. instanceof Determines whether an object is an instance of a class, superclass, or interface. assert Evaluates a conditional expression to verify the programmers assumption.

Primitive types
int 4 bytes short 2 bytes Behaviors is long 8 bytes exactly as in byte 1 byte C++ float 4 bytes double 8 bytes char Unicode encoding (2 bytes) boolean {true,false}

Note: Primitive type always begin with lower-case

Primitive types - cont.

Constants 37 integer 37.2 float 42F float 0754 integer (octal) 0xfe integer (hexadecimal) What will be the output of
int true = 100;

Primitive types
All the 6 types in java are signed The left most bit is used to represent the sign 1 means negative and 0 means positive. The rest of the bits represent the values using 2s complement notation. Octal literals use only digits 0 to 7 and are represented by placing a 0 in front of the number int seven = 07; int eight = 010;

Primitive types
Hexadecimal literals are constructed using 16 distinct symbols. Represented using prefix 0x or the optional suffix extension L.
int x = 0X0001;

Java provides Objects which wrap primitive types and supply methods.
Example: Integer n = new Integer(4); int m = n.intValue();

Read more about Integer in JDK Documentation

Hello World
class Hello { public static void main(String[] args) { System.out.println(Hello World !!!); } }

C:\java Hello

( compilation creates Hello.class ) (Execution on the local JVM)

More sophisticated
class Kyle { private boolean kennyIsAlive_; Default public Kyle() { kennyIsAlive_ = true; } public Kyle(Kyle aKyle) { Ctor kennyIsAlive_ = aKyle.kennyIsAlive_; } public String theyKilledKenny() { if (kennyIsAlive_) { Copy kennyIsAlive_ = false; Ctor return You bastards !!!; } else { return ?; } } public static void main(String[] args) { Kyle k = new Kyle(); String s = k.theyKilledKenny(); System.out.println(Kyle: + s); } }

javac ( to compile )

java Kyle

( to execute )

Kyle: You bastards !!!

Array is an object
Array size is fixed

Animal[] arr; // nothing yet arr = new Animal[4]; // only array of pointers

for(int i=0 ; i < arr.length ; i++) { arr[i] = new Animal();

// now we have a complete array

Arrays - Multidimensional
In C++
Animal arr[2][2]

Is: In Java
Animal[][] arr= new Animal[2][2]

What is the type of the object here ?

Arrays - Multidimensional
String [][][] stringArray; String[] names[];

int[] scores; // declares the array Scores = new int[4]; //constructs an array and assign it; What will be the output of
int[5] scores;

The following code declares and construct a 2-D array int[][] ratings = new int[3][]; The JVM needs to know only the size of the object assigned to the variable. Array elements are given their default values (0, false, null, etc) regardless of whether the array is declared as an instance or local variable. Array of super class can hold sub class objects.

Access Control
public member (function/data)
Can be called/modified from outside.

Can be called/modified from derived classes

Can be called/modified only from the current class

default ( if no access modifier stated )

Usually referred to as Friendly. Can be called/modified/instantiated from the same package.

Default access
A class with default access has no modifier preceding it in the declaration. a class with default access can be seen only by classes within the same package. package cert; class Beverage {} Now look at the second source file: package exam.stuff; import cert.Beverage; class Tea extends Beverage {} >'taccessclasscert.Beverage.Class A default member may be accessed only if the class accessing the member belongs to the same package

Public access
A class declaration with the public keyword gives all classes from all packages access to the public class. Public Members When a method or variable member is declared public, it means all other classes, regardless of the package they belong to, can access the member (assuming the class itself is visible). For a subclass, if a member of its superclass is declared public, the subclass inherits that member regardless of whether both classes are in the same package.

Private Access
Members marked private cant be accessed by code in any class other than the class in which the private member was declared. When a member is declared private, a subclass cant inherit it.

Protected Access
Protected member can be accessed by a subclass even if the subclass is in a different package. Protected does not mean that the subclass can treat the protected superclass member as though it were public. So if the subclassoutside-the-package gets a reference to the superclass the subclass cannot use the dot operator on the superclass reference to access the protected member.

Final Classes When used in a class declaration, the final keyword means the class cant be subclassed. You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden. Java core libraries are final Final Methods The final keyword prevents a method from being overridden in a subclass, and is often used to enforce the API functionality of a method

Final Variables Declaring a variable with the final keyword makes it impossible to reinitialize that variable once it has been initialized with an explicit value. For primitives, this means that once the variable is assigned a value, the value cant be altered. A reference variable marked final cant ever be reassigned to refer to a different object. The data within the object, however, can be modified, but the reference variable cannot be changed.

Static - [1/4]
Member data - Same data is used for all the instances (objects) of some Class.
Class A { public int y = 0; public static int x_ = 1; }; A a = new A(); A b = new A(); System.out.println(b.x_); a.x_ = 5; System.out.println(b.x_); A.x_ = 10; System.out.println(b.x_);
Assignment performed on the first access to the Class. Only one instance of x exists in memory

a Output: 0 y

b 0 y 1 A.x_

1 5 10

Static - [2/4]
Member function
Static member function can access only static members Static member function can be called without an instance. Class TeaPot {
private static int numOfTP = 0; private Color myColor_; public TeaPot(Color c) { myColor_ = c; numOfTP++; } public static int howManyTeaPots() { return numOfTP; } // error : public static Color getColor() { return myColor_; } }

Static - [2/4] cont.

TeaPot tp1 = new TeaPot(Color.RED);

TeaPot tp2 = new TeaPot(Color.GREEN);

System.out.println(We have + TeaPot.howManyTeaPots()+ Tea Pots);

Static - [3/4]
Code that is executed in the first reference to the class. Several static blocks can exist in the same class ( Execution order is by the appearance order in the class definition ). Only static members can be accessed.
class RandomGenerator { private static int seed_; static { int t = System.getTime() % 100; seed_ = System.getTime(); while(t-- > 0) seed_ = getNextNumber(seed_); } } }

abstract member function, means that the function does not have an implementation. abstract class, is class that can not be instantiated. class AbstractTest is an abstract class. It can't be instantiated. new AbstractTest(); ^ 1 error

NOTE: An abstract class is not required to have an abstract method in it. But any class that has an abstract method in it or that does not provide an implementation for any abstract methods declared in its superclasses must be declared as an abstract class.


Abstract - Example
package java.lang; public abstract class Shape { public abstract void draw(); public void move(int x, int y) { setColor(BackGroundColor); draw(); setCenter(x,y); setColor(ForeGroundColor); draw(); } } package java.lang; public class Circle extends Shape { public void draw() { // draw the circle ... } }

String is an Object
Constant strings as in C, does not exist The function call foo(Hello) creates a String object, containing Hello, and passes reference to it to foo. There is no point in writing :
String s = new String(Hello);

The String object is a constant. It cant be changed using a reference to it.

Flow control
Basically, it is exactly like c/c++.
do/while if/else
If(x==4) { // act1 } else { // act2 }
int i=5; do { // act1 i--; } while(i!=0);

char c=IN.getChar(); switch(c) { case a: case b: // act1 break; default: // act2 }

int j; for(int i=0;i<=9;i++) { j+=i; }

Java code has hierarchical structure. The environment variable CLASSPATH contains the directory names of the roots. Every Object belongs to a package ( package keyword) Object full name contains the name full name of the package containing it.

Interfaces are useful for the following: Capturing similarities among unrelated classes without artificially forcing a class relationship.

Declaring methods that one or more classes are expected to implement.

Revealing an object's programming interface without revealing its class.

abstract class

Helps defining a usage contract between classes

All methods are public Javas compensation for removing the multiple inheritance. You can inherit as many interfaces as you want.

- The correct term is to implement an interface



interface IChef { void cook(Food food); }

interface BabyKicker { void kickTheBaby(Baby); }

interface SouthParkCharacter { void curse(); }

class Chef implements IChef, // overridden methods // can you tell why ? public void curse() { public void cook(Food }

SouthParkCharacter { MUST be public

} f) { }

* access rights (Java forbids reducing of access rights)

When to use an interface ?

Perfect tool for encapsulating the classes inner structure. Only the interface will be exposed