Session 1 Introduction to Java Objective How a

Session 1: Introduction to Java

Objective • • How a java code is executed JVM Run simple java codes User interaction Conditional statements. Looping Array (Basic usages)

So Many Language C Perl C++ C# Python Shell Script Basic PHP SQL Java. Script

Java : Introduction • Java is a powerful, object-oriented computer programming language. • Sun Microsystems developed Java in May 1995. • Sun provides an implementation of this platform, called the J 2 SE Development Kit (JDK).

Introduction (contd. ) • Java is a portable language. It supports the notion – “write once, run anywhere”. • Java is both a compiled an interpreted language. • Java can be used to develop a wide variety of applications – Desktop-based applications • Command-line programs • Window-based, interactive programs – Internet-based applications – Client-Server applications – Applications for small hand-held devices like mobile phones, PDAs, etc.

Introduction (contd. ) • Java has three editions. – Java 2 Platform, Standard Edition (J 2 SE) • Used for developing Desktop-based application and networking applications. – Java 2 Platform, Enterprise Edition (J 2 EE) • Used for developing large-scale, distributed networking applications and Web-based applications. – Java 2 Platform, Micro Edition (J 2 ME) • Used for developing applications for small memory-constrained devices, such as cell phones, pagers and PDAs.

Difference Between Programming Languages • Compiled – Complied languages are firstly compiled to machine executable then the machine executable is run. – Ex: C, C++ • Interpreted – Interpreted languages are run from the source code. – Ex: Basic, Visual Basic, PHP, Perl

Compiler • Let’s analyze how computer understands a programming language. Code Compile Run

Interpreter Code Run

Java • Then what about java? • Java is bit different the other languages. • Java usages a hybrid structure, a combination of both compiled and interpreted language. • Code in java is first converted to bit code then JVM (Java Virtual Machine) executes it.

Java Code Execution Flow Code Compile to Bytecode Load in JVM Execution Bytecode Verification

JRE, JDK and JVM • JVM: Java Virtual Machine – the program that loads and runs java bytecode. • JRE: Java Run time Environment – the package you need to have to run java codes. • JDK: Java Development Kit – the package you need to compile java code. (JDK comes with JRE)

Phase 1: Creating a Program • Any text editor or Java IDE (Integrated Development Environment) can be used to develop Java programs. • Java source-code file names must end with the extension. • Some popular Java IDEs are Net. Beans, j. Edit, Eclipse, JBuilder, JCreator etc.

Phase 2: Compiling a Java Program into Bytecodes • Javac Welcome. java – Compiles the source file “Welcome. java” (and other files if necessary), transforms the Java source code into bytecodes and places the bytecodes in a file named “Welcome. class”. – It searches the file “Welcome. java” in the current directory. • Bytecodes – They are not machine language binary code. – They are independent of any particular microprocessor or hardware platform. – They are platform-independent instructions. – Another entity or interpreter is required to convert the bytecodes into machine codes that the underlying microprocessor understands. – This is the job of the JVM (Java Virtual Machine)

JVM (Java Virtual Machine) • It is a part of the JDK and the foundation of the Java platform. • It can be installed separately or with JDK. • A virtual machine (VM) is a software application that simulates a computer, but hides the underlying operating system and hardware from the programs that interact with the VM. • One of the main contributors for the slowness of Java programs compared to compiled machine language programs (i. e. C, C++, Pascal etc. ).

JVM (Java Virtual Machine) (contd. ) • It is the JVM that makes Java a portable language. • The same bytecodes can be executed on any platform containing a compatible JVM. • JVM is available for Windows, Unix, Linux and Solaris. • The JVM is invoked by the “java” command. – java Welcome – It searches the class “Welcome” in the current directory and in the directories listed in the CLASSPATH environment variable and executes the “main” method of class “Welcome”. – It issues an error if it cannot find the class “Welcome” or if class “Welcome” does not contain a method called “main” with proper signature (more on this will be discussed later)

Phase 3: Loading a Program into Memory • One of the components of the JVM is the class loader. • The class loader takes the. class files containing the programs bytecodes and transfers them to primary memory (RAM). • The class loader also loads any of the. class files provided by Java that our program uses. • The. class files can be loaded from a disk on our system or over a network (another PC in our LAN, or the Internet).

Phase 4: Bytecode Verification • Another component of the JVM is the bytecode verifier. • Its job is to ensure that bytecodes are valid and do not violate Java’s security restrictions. • This feature helps to prevent Java programs arriving over the network from damaging our system. • Another contributor for making Java programs slow.

Phase 5: Execution • Now the actual execution of the program begins. • Bytecodes are converted to machine language suitable for the underlying OS and hardware. • Recent JVM performs just-in-time (JIT) compilation to make program execution faster. • So, we can say that Java programs actually go through two compilation phases – – Source code ->bytecodes – Bytecodes -> machine language • Why does Java not follow the following strategy? – Source Code -> JVM -> machine language – Think, think and get some answers.

Let’s Say Hello Java!!

Hello World A Minimum java code is as follows /* File Name: Java. Test. java*/ public class Java. Test { } public static void main(Stringargs[ ]) { System. out. println(“Hello World”); }

Analyzing the Code • Every program in Java consists of at least one class declaration defined by the programmer. • A Java source file can contain multiple classes, but only one class can be a “public” class. • The source file name must match the name of the defined in the file with the. java extension. • By convention, all class names in Java begin with a capital letter and capitalize the first letter of each word they include (e. g. Sample. Class. Name) • Java is case sensitive. In fact Java file names are also case sensitive. Not like sql in oracle.

Compiling a Java Program (Java. Test. java) • Place the source file in the “bin” directory of your Java installation. – C: Program FilesJavajdk 1. x. x_xxbin – (x. x_xx is the version number) • Open a Command Prompt window and go to the “bin” directory. • Execute the following command – – javac. Java. Test. java • If the source code is ok, then javac (the Java compiler) will produce a file called “Java. Test. class” in the current directory (“bin”).

Compiling a Java Program (Java. Test. java) • If the source file contains multiple classes then javac will produce separate. class files for each class. • Every compiled class in Java will have their own. class file having the name of the class with a. class extension. • . class files contain the bytecodes of each class. • So, a. class file in Java contains the bytecodes of a single class only.

Executing a Java Program (Java. Test. class) • Open a Command Prompt window and go to the “bin” directory (or use the same window used in the compilation step). • Execute the following command – – java Java. Test – Note that we have omitted the. class extension here. • Here java (the JVM) will look for the class file Java. Test. class and search for a “public static void main(Stringargs[ ])” method inside the class. • If the JVM finds the above two, it will execute the body of the “main” method. • If the JVM fails to locate the class or fails to find the proper “main” method inside the class, it will generate an error and will exit immediately.

Another test with user input import java. util. Scanner; public class Input. Test { public static void main(Stringargs[ ]) { Scanner input = new Scanner(System. in); System. out. print(“Enter an integer: ”); int num 1 = input. next. Int(); System. out. printf(“You entered: %dn”, num 1); } }

Examining Input. Test. java (contd. ) • The use of “import” is similar to the use of “using namespace” in C++. • Why did we not use “import” to inform the compiler about class System? – Because System resides in the package “java. lang”, which is automatically imported to every Java application. – So, we can use all classes from “java. lang” in our program without explicitly using the “import” statement. • To import all the classes from a package (e. g. java. util) we have to use “import java. util. *; ”

Examining Input. Test. java (contd. ) • We use a Scanner object to wrap the standard input object “System. in”. • We call the method “next. Int()” on the Scanner object “input” to read an integer from the keyboard. • If we enter a non-integer value, an exception is thrown and the program terminates abnormally. Exception Handling is a major topic in Java and will be discussed elaborately later in the course.

Examining Input. Test. java (contd. ) • The variable of a class type is called a. – Here “input” is a reference to a Scanner object. • Merely declaring a class reference is not enough. We have to use “new” to create an object. – Scanner input; • Does not point to or represent any object. • Cannot be used for any useful purpose until we create an object of class Scanner using “new” and assign the returned address/object to “input”. • Or, we may call a function that returns an object of class Scanner and assign it to “input”.

The boolean Data Type • A primitive data type in Java • Can have only two values – true – false • Both and false are keywords in Java • Does not have any relation with int – booleanb = false; – int a = b; // compiler error – int a = (int)b; // compiler error

if, if … else Statements if(condition) { …} else { …} if(condition) { …} else if (condition) else { …} • The condition. MUST BE a boolean expression • Generally comparison operators (==, != <=, > etc. ) produce boolean values • Logical operators (&&, ||, &, | etc. ) are used to combine multiple booleanexpressions

if, if … else Statements (contd. ) • Let, – int i = 0; – if( i ) // want to check whether ‘i’ is non-zero • Compiler error • Condition MUST BE a boolean value – if ( i != 0 ) • No problem

Conditional Operator • (condition)? (X): (Y) – X = Value of the conditional expression if condition is – Y = Value of the conditional expression if condition is • The condition. MUST BE a boolean expression • This is Java’s only

while Repetition Statement • while(condition) { …} • The condition. MUST BE a boolean expression • Can be counter controlled or sentinel controlled

Primitive Types • There are eight primitive types in Java – boolean, byte, char, short, int, long, float, double – All values (integer and floating point) in Java are signed; there is no unsigned data type • Java requires all variables to have a type • Java is referred to as a
![Loop public class Loop. Test { public static void main(String[] args) { System. out. Loop public class Loop. Test { public static void main(String[] args) { System. out.](http://slidetodoc.com/presentation_image_h2/9bbb8fa605d793b69d1e48cc839f9e74/image-36.jpg)
Loop public class Loop. Test { public static void main(String[] args) { System. out. println("Number from 1 to 100: "); for (inti = 0; i< 100; i++) { System. out. print(i + " "); } System. out. println(); } }
![Array public class Array. Test { public static void main(String[] args) { String[] names Array public class Array. Test { public static void main(String[] args) { String[] names](http://slidetodoc.com/presentation_image_h2/9bbb8fa605d793b69d1e48cc839f9e74/image-37.jpg)
Array public class Array. Test { public static void main(String[] args) { String[] names = new String[3]; names[0] = "Shakib Al Hasan"; names[1] = "Tamim. Iqbal"; names[2] = "Shafiul Islam"; System. out. println("First Name: " + names[0]);

Array (Cont. ) System. out. println("List of names: "); for (inti = 0; i<names. length; i++) { System. out. println(names[i]); } } }

For-Each Loop for (String name : names) { System. out. println(name); }
- Slides: 39