You are on page 1of 14

United International University Trimester: Fall 2009 Course: CSI 211 Course Title: Object Oriented Programming Lecture

1a: Java Introduction

What is Java?
A Language A Platform An OS A Chip

Java - Characteristics
Uses C/C++ basic syntax and basic data types -int, char, float, double, long, short, byte etc. Uses standard C/C++ control structures Pure OO language No stand alone functions -All code is part of a class No explicit pointers - uses references Uses garbage collection Java is strongly typed

Java More characteristics


Java is normally compiled to a bytecode ;Java bytecode is a machine language for an abstract machine Each platform (or browser) that runs Java has a Java Virtual Machine (JVM or sometimes VM) . The JVM executes Java bytecodes JVMs with Just-In-Time (JIT) compilers will:

UIU Lecture 1a, CSI 211

1/14

Compile the bytecodes to native machine code This is done for each method the first time is executed The native machine code is cached The JVM then runs the native machine code for the method

Java 1.2 will have a JVM (Hotspot) that runs Java code much faster than simple JIT JVMs Other languages can be compiled to Java's bytecode An Ada compiler exists that compiles Ada to Java bytecode

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 Java Interface Definition Language (IDL) - CORBA JDBCTM Database Access JavaBeansTM - componentware JavaTM Communications API - serial & parallel port JavaHelpTM JavaTM Advanced Imaging JavaTM Web Server TM PersonalJavaTM - Java on personal consumer devices EmbeddedJavaTM - Java on embedded devices JavaTM Card TM - Java on a smart card JavaTM Naming and Directory Interface TM (JNDI) Java Message Service (JMS)

UIU Lecture 1a, CSI 211

2/14

Java - The OS
Sun and IBM are implementing the Java OS which is an operating system that executes the Java environment directly on hardware platforms

Java - The Chip


Some companies are implementing hardware that uses the Java bytecode as native machine code

Versions of Java
JDK(Java Development Kit) 1.0.2 o First widely used version o All browsers with Java support this version JDK 1.1.X Current release is JDK 1.1.6 o Made changes to the language from JDK 1.0.X o Add inner classes , Generics o API is about 3 times larger than 1.0.2 o Event model for GUI components changed from 1.0.2 JDK 1.2 -Currently in beta 4 o API is about 3 times larger than 1.1.X, so lots of new stuff o Should contain major performance increases o Major additions to GUI components

JAVA IDE
Using JDK you can compile and run java program from command line. o c:> javac HelloWorld. java - compiling here and it will produce HelloWorld.class i.e. bytecode. o c:>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: o Eclipse - from IBM o Netbeans

UIU Lecture 1a, CSI 211

3/14

o Jbuilder from Borland o Visual Studio J++ - from microsoft o Visual Cafe from Webgain.

UIU Lecture 1a, CSI 211

4/14

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

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

UIU Lecture 1a, CSI 211

5/14

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; char c; c = 'a'; // This is legal in Java

} }

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" ); } }

UIU Lecture 1a, CSI 211

6/14

Style #2 class Syntax { // brace starts public static void main( String args[] ) { int aVariable = 5; if ( aVariable < aFloat ) System.out.println( "True" ); } } Style#3 class Syntax {// brace starts public 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 abbreviation)

Variable and function names starts with a lowercase letter and after that use Title case Examples:variableAndFunctionNames aFloat, studentName Names of constants All are capital letters and separated by underscore. Example is NAMES_OF_CONSTANTS

UIU Lecture 1a, CSI 211

7/14

Example of Keywords - do not use for any naming abstract boolean break byte case catch char class const continue default do double else extends final finally float for if implements import instanceof int interface long native new package private protected public return short static super switch synchronized this throw throws transient try void volatile while

Reserved for possible future use (not used now) byvalue inner cast operator future outer generic rest goto var

Boolean true, false act like keywords but are boolean constants
public class BooleanTest { public static void main( String args[] ){ boolean flag = 2 > 3; if ( flag && true) System.out.println( "True" ); else System.out.println( "False" ); } }

Input and Output


Standard Java Output System.out is standard out in Java System.err is error out in Java

UIU Lecture 1a, CSI 211

8/14

class Output { public static void main( String args[] ) { // Standard out System.out.print( "Prints, but no newline" ); System.out.println( "Prints, adds platforms newline at end" ); double test = 4.6; System.out.println( test ); System.out.println( "You can use " + "the plus operator on " + test + " String mixed with numbers" ); System.out.println( 5 + "\t" + 7 ); System.out.println( "trouble" + 5 + 7 ); //Problem here System.out.println( "ok" + (5 + 7) ); System.out.flush(); // flushes output buffer System.err.println( "Standard error output" ); } }

Output
Prints, but no linefeed Prints, adds linefeed at end 4.6 You can use the plus operator on 4.6 String mixed with numbers 5 7 trouble57 ok12 Standard error output

Standard Java Input Java assumes that you will be using a GUI for input from the user Hence there is no "simple" way to read input from a user Scanner class is in jdk 1.5

package lecture01; import java.util.Scanner; public class TestInput { public static void main( String[] args ){ Scanner scanner = new Scanner(System.in); System.out.print("Write your name: "); String userName = scanner.nextLine(); System.out.println("Your name is : " + userName);

} }

Output

Write your name: Monzurur Rahman Your name is : Monzurur RahmanYou typed:

34

UIU Lecture 1a, CSI 211

9/14

Basic Data Types


class PrimitiveTypes { public static void main( String args[] ) { // Integral Types byte aByteVariable; // 8-bits short aShortVariable; // 16-bits int aIntVariable; // 32-bits long aLongVariable; // 64-bits // Floating-Point Types float aFloatVariable; // 32-bit IEEE 754 float double aDoubleVariable; // 64-bit IEEE 754 float // Character Type char aCharVariable; // always 16-bit Unicode // Boolean Types boolean aBooleanVariable; // true or false } }

Arithmetic Literals
class ArithmeticLiterals { public static void main( String args[] ) { long aLong = 5L; long anotherLong = 12l; int aHex = 0x1; int alsoHex = 0X1aF; int anOctal = 01; int anotherOctal = 0731; long aLongOctal = 012L; long aLongHex = 0xAL; float aFloat = 5.40F; float alsoAFloat = 5.40f; float anotherFloat = 5.40e2f; float yetAnotherFloat = 5.40e+12f; float compileError = 5.40; //Need cast here double aDouble = 5.40; //Double is default!! double alsoADouble = 5.40d; double moreDouble = 5.40D; double anotherDouble = 5.40e2; double yetAnotherDouble = 5.40e+12d; } }

UIU Lecture 1a, CSI 211

10/14

Operations on Primitive Types Integer Type Equality Relational Unary Arithmetic Pre, postfix increment/decrement Shift Unary Bitwise logical negation Binary Bitwise logical operators = != < <= > >= ++-*/% ++ -<< >> >>> ~ &|^

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: 4 System.out.println( a >> 1); // Shift right: 1 System.out.println( ~a ); // bitwise negation: -3 System.out.println( a | b); // bitwise OR: 6 System.out.println( a ^ b); // bitwise XOR: 6 System.out.println( a & b); // bitwise AND: 0 } }

Floating-Point Types Operations Equality Relational Unary Arithmetic Pre, postfix increment/decrement = != < <= > >= ++-*/% ++ --

UIU Lecture 1a, CSI 211

11/14

NaN, +, - Zero divide with floating-point results in +, - Overflow results in either +, -. Underflow results in zero. An operation that has no mathematically definite result produces NaN - Not a Number NaN is not equal to any number, including another NaN

class NaN { public static void main( String args[] ) { float size = 0; float average = 10 / size; float infinity = 1.40e38f * 1.40e38f; System.out.println( average ); // Prints Infinity System.out.println( infinity ); // Prints Infinity } }

Casting
class Casting { public static void main( String args[] ) { int anInt = 5; float aFloat = 5.8f; aFloat = anInt; // Implicit casts up are ok anInt = aFloat ; // Compile error, // must explicitly cast down anInt = (int) aFloat ; float error = 5.8; // Compile error, 5.8 is double float 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 divide int zero = 0; int trouble = 5 / zero; //Some compilers may give error here int notZeroYet;

UIU Lecture 1a, CSI 211

12/14

notZeroYet trouble = }

= 0; 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 error System.out.println( "C way does not work" ); boolean cantCastFromIntToBoolean = (boolean) 0; // compile error int x = 10; int y = 5; if ( x = y ) // Compile error System.out.println( "This does not work in Java " ); } }

Default Values of Variables


All arithmetic variables (int, float, double) are initialize to 0 char variables are initialize to the null character: '\u000' boolean variables are initialize to false reference variables are initialize to null

Compiler usually complains about using variables before explicitly giving them a value
class InitializeBeforeUsing { public static void main( String args[] ) { int noExplicitValue; System.out.println( noExplicitValue ); // Compile error int someValue; boolean tautology = true; if ( tautology ) { someValue = 5; } System.out.println( someValue ); // Compile error } }

UIU Lecture 1a, CSI 211

13/14

Characters
class CharactersLiterals { public static void main( String args[] ) { char backspace = '\b'; char tab = '\t'; char linefeed = '\n'; char formFeed = '\f'; char carriageReturn = '\r'; char doubleQuote = '\"'; char singleQuote = '\''; char aCharacter = 'b'; char unicodeFormat = '\u0062'; } }

// 'b'

Unicode Superset of ASCII Includes: ASCII, Latin letter with diacritics Greek, Cyrillic Korean Hangul Han ( Chinese, Japanese, Korean ) *************** End of Lecture 1a **************

UIU Lecture 1a, CSI 211

14/14

You might also like