Java Basics Introduction to Java
Topics To Be Covered Objectives Introduction Features of Java Java Architecture Java Program Structure Data Types in Java Operations in Java Console Input and Output Control Structures Summary Quiz
Objectives At the end of this course, you will be able to: Understand the Java Platform Architecture Features of Java Write programs using variables, expressions, console input/output Data types and Operations in Java Write programs using Control Structures
Introduction A high-level programming language Operating System Independent Runs on Java Virtual Machine (JVM) A secure operating environment that runs as a layer on top of the OS A sandbox which protects the OS from malicious code True Object-Oriented Programming language In Java, everything is a class Unlike C++, OOP support is a fundamental component in Java
Features of Java
Features of Java Simple Compares to earlier OO languages like C++, it is simple Robust Puts a lot of emphasis on early checking for possible problems, later dynamic (runtime) checking, and eliminating situations that are error-prone Secure Absence of pointers Support for Multithreading at the language level Designed to handle Distributed applications Architecture Neutral/Portable: Java code compiled on Windows can be run on Unix without recompilation www.prolearninghub.com
Features of Java Platform Independence A platform is the hardware & software environment in which a program runs Once compiled, java code runs on any platform without recompiling or any kind of modification “Write Once Run Anywhere” This is made possible by Java Virtual Machine (JVM)
Java Overview JAVA is platform independent language which means that the program made in java run on any operating system either it is window, IOS or Linux. JAVA syntax is similar to C++. A significant feature in java is multithreading. Several programs run at the same time in JAVA environment.
Java Overview The reason behind JAVA independency is : It only depend on Java virtual Machine(JVM) Code is compiled in bytecode, which is interpreted by JVM.
Java Architecture
Java Architecture Class Loader Source File (HelloWorld.java) Compiler (javac) Class Loader Byte Code Verifier Interpreter Runtime JIT Code Generator Machine Code or Byte code (HelloWorld.class) Operating System Hardware www.prolearninghub.com
Java Architecture JDK Directory Structure After installing the Java software version 1.5, the JDK directory will have the structure as shown JDK Installation Directory lib bin … The bin directory contains both, the computer and the interpreter www.prolearninghub.com
Write a Program Compiling Running Java Architecture Java Development Process Write a Program Compiling Running Compiler Interpreter Java Files Public Class System .class File 010101010101010101010 www.prolearninghub.com
Java Architecture Java Virtual Machine (JVM) We can write a Java program using any text editor or an IDE like Eclipse (Version 3.2 onwards preferred). The source code of Java is stored in a text file with the extension .java The Java compiler complies a .java file into byte code The byte code will be in a file with extension .class The generated .class file is the machine code of this processor Byte code is a binary language The byte code is interpreted by the JVM JVM makes Java platform independent The JVM interprets the .class file to the machine language of the underlying platform The underlying platform processes the commands given by the JVM www.prolearninghub.com
Java Architecture Environment Variables in JVM JAVA_HOME: Java Installation Directory Used to derive all other environment variables used by JVM In Windows set JAVA_HOME=C:\jdkxxxx In Unix export JAVA_HOME=/var/usr/java CLASSPATH Used to locate class files In Windows set CLASSPATH=%CLASSPATH%;%JAVA_HOME%\lib\tools.jar In Unix set CLASSPATH=$CLASSPATH:$JAVA_HOME%/lib/tools.jar PATH Used by OS to locate executable files In Windows set PATH=%PATH%;%JAVA_HOME%\bin In Unix set PATH=$PATH:$JAVA_HOME/bin www.prolearninghub.com
Java Program Structure
Java Program Structure Source File Layout – Hello World Type the source code using Eclipse (Version 3.2 onwards) or any text editor public class HelloWorldApp { public static void main(String[ ] args){ System.out.println("Hello World!"); } Save this file as HelloWorldApp.java www.prolearninghub.com
Java Program Structure To Compile Open the command prompt Set the environment variables Go to the directory in which the program is saved Type – javac HelloWorldApp.java If it says, “bad command or file name” then check the path setting If returns to prompt without giving ant message, it means that compilation is successful www.prolearninghub.com
Java Program Structure To Execute Type the command - java HelloWorldApp The result will be www.prolearninghub.com
Java Program Structure Compilation & Execution Java Program (.java) Java Complier (.javac) Byte Code (.class file) Interpreter (java) Win 32 Linux Mac www.prolearninghub.com
Java Program Structure Java Keywords abstract continue if int switch boolean float import return synchronized break default false package static byte do interface private try case double long protected throws catch else goto* native this char extends new public transient class final implements throw void true finally instanceof short volatile const* for null super while www.prolearninghub.com
Java Program Structure Java Identifiers Declared entities such as variables, methods, classes & interfaces are Java Identifiers Must begin with a letter, underscore (_) or dollar sign ($) May contain letters, digits, underscore (_) & dollar sign ($) www.prolearninghub.com
How Java program Works In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. The java launcher tool then runs your application with an instance of the Java Virtual Machine. www.prolearninghub.com
How Java program Works Compiler Java VMr 01001… MyProgram.java MyProgram.class MyProgram www.prolearninghub.com
Java Environment Setup We now explain the commonly used steps in creating and executing a JAVA application using Java Development environment. There are five phases of creating and executing JAVA program: Edit Compile Load Verify Execute www.prolearninghub.com
Java Environment Setup Editor Compiler Class Loader Bytecode Verifier Java Virtual Machine (JVM) Phrase 1: Edit Phrase 2: Compile Phrase 3: Load Phrase 4: Verify Phrase 5: Execute Disk Primary Memory Program is created in an editor and stored on disk in a file ending with .java Compiler create bytecodes and stores them on disk in a file ending with .class Class loader reads .class files containing bytecodes from disk and puts those bytecodes in memory. Bytecode verifier confirms that all bytecodes are valid and do not violate java’s security restrictions To execute the program, the JVM reads bytecodes and translates them into a language that the computes can understand. As the program executes, it may store data values in primary memory. www.prolearninghub.com
Java Basic Syntax A typical JAVA program has objects, classes, methods and instance. Case Sensitivity: JAVA is case sensitive language. Word and word would have different meaning in JAVA. Class-naming conventions: You can name classes pretty much however you want, but the convention is to use camel case. Start with an uppercase letter, capitalize the first letter of each concatenated word, and make all the other letters lowercase. Example HelloClass www.prolearninghub.com
Sample Program #1 Java Sample Programs public class FirstJavaProgram { public static void main(String[] args){ System.out.println("This is my first program in java"); } //End of main }//End of FirstJavaProgram Class www.prolearninghub.com
Sample Program # 2 Java Sample Programs class Example{ public Static void main(String args[]){ // This is simple JAVA program System.out.print(“ This is simple JAVA program ”); } www.prolearninghub.com
Java Basic Syntax Method Naming Conventions: All method name start with lowercase. If method name is made by more then one words then each word has first capital latter. Program Name: Program file name should match with class name with extension of ’ .java ’ . Example your class name is HelloWorld then file name should be HelloWorld.java . public static void main(String args[]) : Java program processing starts from the main() method which is a mandatory part of every Java program. www.prolearninghub.com
Data Types in Java
Data Types in Java Java is a strongly typed language Data types may be Unlike C, Type checking is strictly enforced at run time Impossible to typecast incompatible types Data types may be Primitive data types Reference data types www.prolearninghub.com
Data Types in Java Primitive Data Types in Java Integer Data Types byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes) All numeric data types are signed The size of data types remain same on all platforms Char data type is 2 bytes as it uses the UNICODE character set. And so, Java supports internationalization Floating Data Types float (4 bytes) double (8 bytes) Character Data Types char (2 byte) Logical Data types boolean (1 bit) (true/false) www.prolearninghub.com
Data Types in Java Variables A named storage in the computer’s memory that stores a value of a particular type for use by program Example of variable declaration: The data type can either be: built-in primitive types (e. g. int, double, char) Reference data types (e.g. String, BufferedReader) Naming Convention: Variable Name: First word lowercase & rest with their initials capitalized (Camel Casing) e.g. thisIsALongVariableName DataType VariableName int myAge, cellPhone ; double salary ; char tempChar ; www.prolearninghub.com
Data Types in Java Variables (Contd…) Using primitive data types is similar to other languages Variables can be declared anywhere in the program In Java, if a local variable is used without initializing it, the compiler will show an error int count ; int max=100; for (int count=0; count <max; count++) { int z = count * 10; } BEST PRACTICE: Declare a variable in program only when required Do not declare variables upfront like in C www.prolearninghub.com
Data Types in Java Comments in Java A single line comment in Java starts with // A multi line comment starts with /* & ends with */ // This is a single line comment in Java /* This is a multi line comment in Java */ www.prolearninghub.com
Data Types in Java Reference Data Types Hold the reference of dynamically created objects which are in the heap Can hold three kinds of values: Class type: Points to an object / class instance Interface type: Points to an object which is implementing the corresponding interface Array type: Points to an array instance or “null” Difference between Primitive & Reference data types: Primitive data types hold values themselves Reference data types hold reference to objects, i.e. they are not objects, but reference to objects Objects & Arrays are accessed using reference variables in Java A reference variable Is similar to a pointer (stores memory address of an object) Java does not support the explicit use of addresses like other languages www.prolearninghub.com
Data Types in Java Reference Data Types (Contd…) Java does not allow pointer manipulation or pointer arithmetic Memory Representation: primitive reference A reference type cannot be cast to a primitive type A reference type can be assigned ‘null- to show that it is not referring to any int primitive = 5; String reference = “Hello” ; 5 Hello www.prolearninghub.com
Data Types in Java Typecasting Primitive Data Types Automatic type changing is known as Implicit Conversion - A variable of smaller capacity can be assigned to another variable of bigger capacity Whenever a larger type is converted to a smaller type, we have to explicitly specify the type cast operator This prevents any accidental loss of data int i = 10; double d; d = i; double d = 10; d = i; i = (int) d; Type cast operator () www.prolearninghub.com
Operations in Java
Operations in Java Used to manipulate primitive data types Classified as unary, binary or ternary Following are different operators in Java: Assignment Arithmetic Relational Logical Bitwise Compound assignment Conditional Java Operations Assigment Operators = Arithmetic Operations - + * / % ++ - - Relational Operators > < >= <= == != Logical Operators && || & | ! ^ Bit wise Operator & | ^ >> >>> Compound Assignment Operators += -= *= /= %= <<= >>= >>>= Conditional Operator ?: www.prolearninghub.com
Operations in Java Precedence & Associativity of Java Operators Decides the order of evaluation of operators
Console Input and Output
Console Input and Output Accepting Data from Keyboard import java.util.Scanner; public class Datalnput { public static void main(String args[ ]) { Scanner input = new Scanner(System.in); System.out.println("Enter First Number-); int a = input.nextlnt(); System.out.println("Enter Second Number"); int b = input.nextlnt(); int c = a + b; System.out.prlntln(“Addition is..." + c); } Like nextInt ( ) method,which scans the integer value, the Scanner class provides methods for other data types as well. www.prolearninghub.com
Control Structures
Control Structures Work the same as in C / C++ if/else, for, while, do/while, switch i = 0; while(i < 10) { a += 1; i++; } do { a += i; } while(i < 10); if(a > 3) { a = 3; else { a = 0; for(i = 0; i < 10; i++) { switch(i) { case 1: string = “foo”; case 2: string = “bar”; default: string = “”; www.prolearninghub.com
Control Structures (Contd…) Java supports continue & break keywords also Again, works very similar to C / C++ Switch statements require the condition variable to be of char, byte, short or int type for(i = 0; i < 10: i++) { if(i == 5) continue; a += i; } for(i = 0; i < 10: i++) { a += i; if(a > 100) break; } www.prolearninghub.com
Summary
Summary In this session, we have covered: Java Architecture Features of Java Data types and Operators in Java Control Structures www.prolearninghub.com
Assessment – Java Basics: Part1 The quiz contains 10 questions. You will have one attempt to answer each question. You can exit the quiz at any time. If you exit the quiz without completing all 10 questions, on return you will have to start the quiz from the beginning. Scoring 80% or higher means you have understood the topic well. Start www.prolearninghub.com
Java Is Strongly Typed Language True False
Which of the following is not a feature of Java? Multithreaded Object Oriented Platform Dependent
Conditional Operator (?:) Which of the following operator in Java has associativity as Right to Left? Conditional AND (&& ) Conditional Operator (?:) Conditional OR ( II ) www.prolearninghub.com
Find the odd one from below while do while Untill while www.prolearninghub.com
Because of which Java is Platform Independent? KVM JVM HVM www.prolearninghub.com
Which of the following is not accepted by Reference Variable? Integer variable Array Object www.prolearninghub.com
Which of the following loads a .class file in memory? Byte code verifier Class Loader JIT Code generator www.prolearninghub.com
Which of the following is not a valid identifier? basicSal 12Number empHra www.prolearninghub.com
Suppose x is a local variable in main method Suppose x is a local variable in main method. If we print its value without initializing it then what will happen? Will print 0 Will print 1 Compile time error www.prolearninghub.com
Why Java is a Secure programming language? Absence of Pointers Absence of Multithreading Absence of Robustness www.prolearninghub.com
The Results