Engineered for Tomorrow Unit 1 Introduction to Java

  • Slides: 133
Download presentation
Engineered for Tomorrow Unit -1 Introduction to Java Engineered for Tomorrow 25/07/2014

Engineered for Tomorrow Unit -1 Introduction to Java Engineered for Tomorrow 25/07/2014

Engineered for Tomorrow Introduction to Java is an object-oriented, high level programming language developed

Engineered for Tomorrow Introduction to Java is an object-oriented, high level programming language developed by Sun Microsystems in 1991 by James Gosling. The features of Java Ø Java program is both compiled and interpreted. Ø Write once, run anywhere. Ø Java is a software-only platform running on top of other, hardware-based platforms. Ø Java Virtual Machine (Java VM) Ø The Java Application Programming Interface (JAVA API)

Engineered for Tomorrow History of Java • Originally called as Oak. • Developed Hot.

Engineered for Tomorrow History of Java • Originally called as Oak. • Developed Hot. Java-The first Java-enabled Web browser • JDK Evolutions • • • J 2 SE, J 2 ME, and J 2 EE. JDK 1. 02 (1995) JDK 1. 1 (1996) Java 2 SDK v 1. 2 (JDK 1. 2, 1998) Java 2 SDK v 1. 3 (JDK 1. 3, 2000) Java 2 SDK v 1. 4 (JDK 1. 4, 2002)

Engineered for Tomorrow JDK Editions • Java Standard Edition (J 2 SE) J 2

Engineered for Tomorrow JDK Editions • Java Standard Edition (J 2 SE) J 2 SE can be used to develop client-side standalone applications or applets. • Java Enterprise Edition (J 2 EE) J 2 EE can be used to develop server-side applications such as Java servlets and Java Server. Pages. • Java Micro Edition (J 2 ME). J 2 ME can be used to develop applications for mobile devices such as cell phones.

Engineered for Tomorrow Applications of Java • Stand-alone Applications Just like any programming language

Engineered for Tomorrow Applications of Java • Stand-alone Applications Just like any programming language • Applet Run under a Java-Enabled Browser • Midlet Run in a Java-Enabled Mobile Phone • Servlet Run on a Java-Enabled Web Server • Switchlet

Engineered for Tomorrow JDK - Java Development Kit • The Java Development Kit contains

Engineered for Tomorrow JDK - Java Development Kit • The Java Development Kit contains the software and tools that you need to compile, debug, and run applets and applications that you've written using the Java programming language. • JDK is available free from SUN Microsystems, the creators of the Java programming language (http: //java. sun. com/products/jdk/).

Engineered for Tomorrow Basic command-line tools in the (JDK) • javac -Is the Java

Engineered for Tomorrow Basic command-line tools in the (JDK) • javac -Is the Java compiler. Java source code (file with a javac. java extension) is compiled into Java bytecodes (class file, extension. class). • java - Is the Java Interpreter, it executes Java class files. java • jdb - Is a command-line debugger for Java classes. jdb • appletviewer - Is the Java applet viewer, it allows you to appletviewer run applets without a web browser. • javah - Is used to integrate C and Java. javah • javap - Disassembles class files. javap • javadoc - Generates documentation from a Java source javadoc file

Engineered for Tomorrow Architecture of JDK

Engineered for Tomorrow Architecture of JDK

Engineered for Tomorrow Java Buzzwords • • • Simple Object-Oriented Network Savvy Interpreted Robust

Engineered for Tomorrow Java Buzzwords • • • Simple Object-Oriented Network Savvy Interpreted Robust Secure Architecture Neutral Portable High-Performance Multithreaded Dynamic

Engineered for Tomorrow Java Is Simple • • • Simpler than C++ Many keywords

Engineered for Tomorrow Java Is Simple • • • Simpler than C++ Many keywords have been eliminated No preprocessor Much larger library of high-level development tools No operator overloading No independent functions No global variables No goto statement No structures No pointers

Engineered for Tomorrow Java Is Object-Oriented • The only unit of programming is the

Engineered for Tomorrow Java Is Object-Oriented • The only unit of programming is the class description. • No functions or variables exist outside of class boundaries. • Other languages have object-oriented features on top of the non-object-oriented language. • Forces all programs into object-oriented structure. • Many benefits of object-oriented design is realized.

Engineered for Tomorrow Java Is Network Savvy • Designed with Internet in mind. •

Engineered for Tomorrow Java Is Network Savvy • Designed with Internet in mind. • It is possible to construct programs that do not deal with Internet. • Provides a rich set of tools for programming across a network. • Classes for describing URLs. • Classes for making connections between client and server computers. • Classes for execution in controlled environments such as web browsers.

Engineered for Tomorrow Java Is Interpreted • Java programs are compiled into byte-code that

Engineered for Tomorrow Java Is Interpreted • Java programs are compiled into byte-code that can be stored on any type machine. • Interpreter is used to read byte-code and execute it • Generally slower in execution. • A JIT compiler is used to translate byte-code into actual machine code instructions. • This way makes them run as fast as compiled programs in the traditional languages.

Engineered for Tomorrow Java Is Robust • Extensive use of exception-handling. • Statements generate

Engineered for Tomorrow Java Is Robust • Extensive use of exception-handling. • Statements generate exceptions not erroneous operations • The semantics insist that you must deal with this possibility • Programmers are forced into thinking about potential sources of error • Automatic memory management, or garbage collection • If programmers forget to release memory resources once finished with them, applications will eventually fail • Java run-time system automatically detects and recovers memory that is no longer being used by the program • Simplifies the programmer’s task and is more reliable

Engineered for Tomorrow Java Is Secure • Eliminating pointers removed the most common source

Engineered for Tomorrow Java Is Secure • Eliminating pointers removed the most common source of programming errors • Array index values are checked for validity • Java is the first layer in a multilevel security system • Byte-codes are examined before executed for errors • Programs are severely restricted in the type operations they can perform • Computers are safe when running java programs brought over the network

Engineered for Tomorrow Java Is Architecture Neutral • Java byte-code does not correspond to

Engineered for Tomorrow Java Is Architecture Neutral • Java byte-code does not correspond to an machine • A java program is the same on all machines • Although C++ is a standard language, the libraries needed to perform activities differ considerably from platform to another • Java hides application-specific details under a layer of abstraction in the standard java library

Engineered for Tomorrow Java Is Portable • Because the library hides architecture-specific concepts •

Engineered for Tomorrow Java Is Portable • Because the library hides architecture-specific concepts • Because byte-codes are the same regardless of the machine • Java programs possess unparalleled degree of portability • The exact program can be compiled on one system, then executed on many different types of systems

Engineered for Tomorrow Java Is High-Performance • Initially heavy performance penalty. • The technology

Engineered for Tomorrow Java Is High-Performance • Initially heavy performance penalty. • The technology of java execution has rapidly evolved. • JIT compilers allow platform-independent java programs to be executed with the nearly same run-time performance as conventional compiled languages.

Engineered for Tomorrow Java Is Multithreaded • One of the first languages designed for

Engineered for Tomorrow Java Is Multithreaded • One of the first languages designed for the possibility of multiple threads of execution running in one program. • It is easy to set up multitasking. • The coordination of these parallel processes is relatively easy.

Engineered for Tomorrow Java Is Dynamic • Moving java programs across the Internet and

Engineered for Tomorrow Java Is Dynamic • Moving java programs across the Internet and executing them on local computers, permits dynamic behavior

Engineered for Tomorrow OOP principles • ü ü Four principles of object oriented programming:

Engineered for Tomorrow OOP principles • ü ü Four principles of object oriented programming: Data Abstraction Encapsulation Inheritance Polymorphism • Data abstraction - Any representation of data in which the implementation details are hidden (abstracted). -Abstract data types and objects are the two primary forms of data abstraction.

Engineered for Tomorrow • Encapsulation -The ability to provide users with a well-defined interface

Engineered for Tomorrow • Encapsulation -The ability to provide users with a well-defined interface to a set of functions in a way which hides their internal workings. -In oop, the technique of keeping together data structures and the methods (procedures) which act on them. • Inheritance -The ability to derive new classes from existing classes. -A derived class (or "subclass") inherits the instance variables and methods of the base class and may add new instance variables and methods.

Engineered for Tomorrow -New methods may be defined with the same names as those

Engineered for Tomorrow -New methods may be defined with the same names as those in the base class, in which case they override the original one. -For example, bytes might belong to the class of integers for which an add method might be defined. The byte class would inherit the add method from the integer class. • Polymorphism -Polymorphism refers to the ability to define multiple classes with functionally different, yet identically named methods or properties that can be used interchangeably by client code at run time.

Engineered for Tomorrow Data Abstraction • It refers to the ability to make a

Engineered for Tomorrow Data Abstraction • It refers to the ability to make a class abstract in OOP. • An abstract class is one that cannot be instantiated. • All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. • Can’t create an instance of the abstract class. • Use the abstract keyword to declare a class abstract. • The keyword appears in the class declaration somewhere before the class keyword.

Engineered for Tomorrow Example Program abstract class Class. A { int x, y; void

Engineered for Tomorrow Example Program abstract class Class. A { int x, y; void method 1(int X, int Y) {} abstract void method 2(); abstract void method 3(); } public class Class. B extends Class. A{ void method 2() { System. out. println("this is Method 2 of class B"); } void method 3() { System. out. println("this is Method 3 of class B"); } }

Engineered for Tomorrow Example Program(Contd. . ) public class Main. Class{ public static void

Engineered for Tomorrow Example Program(Contd. . ) public class Main. Class{ public static void main(String[] args) { Class. A obj 1= new Class. B(); obj 1. method 2(); obj 1. method 3(); } } Output: this is Method 2 of class B this is Method 3 of class B

Engineered for Tomorrow Encapsulation • Encapsulation is the ability to package data, related behavior

Engineered for Tomorrow Encapsulation • Encapsulation is the ability to package data, related behavior in an object bundle and control/restrict access to them (both data and function) from other objects. It is all about packaging related stuff together and hide them from external elements. • Hiding an attribute or method is easier from the outer world. Just use the access specifier ‘private’.

Engineered for Tomorrow Example Program //save as Student. java package com. javapgm; public class

Engineered for Tomorrow Example Program //save as Student. java package com. javapgm; public class Student{ private String name; public String get. Name(){ return name; } public void set. Name(String name){ this. name=name } } //save as Test. java package com. javapgm; class Test{ public static void main(String[] args){ Student s=new Student(); s. setname("vijay"); System. out. println(s. get. Name()); } Output: vijay

Engineered for Tomorrow Inheritance • It is a process where one object acquires the

Engineered for Tomorrow Inheritance • It is a process where one object acquires the properties of another object. • With the use of inheritance the information is made manageable in a hierarchical order. • It is achieved by using extends keyword. • Only properties with access modifier public and protected can be accessed in child class.

Engineered for Tomorrow Example Program class A { public A() { System. out. println("New

Engineered for Tomorrow Example Program class A { public A() { System. out. println("New A"); } } class B extends A { public B() { super(); System. out. println("New B"); } Output: New A New B

Engineered for Tomorrow Polymorphism • Polymorphism means the ability to take on many forms,

Engineered for Tomorrow Polymorphism • Polymorphism means the ability to take on many forms, The term is applied both to objects and to operations. • Polymorphism is tightly coupled to inheritance and is one of the most powerful advantages to object-oriented technologies. • Polymorphic operation - "One Operation, Many Methods".

Engineered for Tomorrow Example Program class Overload { void demo (int a) { System.

Engineered for Tomorrow Example Program class Overload { void demo (int a) { System. out. println ("a: " + a); } void demo (int a, int b) { System. out. println ("a and b: " + a + ", " + b); } double demo(double a) { System. out. println("double a: " + a); return a*a; } }

Engineered for Tomorrow Example Program(Contd. . ) class Method. Overloading { public static void

Engineered for Tomorrow Example Program(Contd. . ) class Method. Overloading { public static void main (String args []) { Overload Obj = new Overload(); double result; Obj. demo(10); Obj. demo(10, 20); result = Obj. demo(5. 5); System. out. println("O/P : " + result); } }

Engineered for Tomorrow Programming in Java. • We break the process of programming in

Engineered for Tomorrow Programming in Java. • We break the process of programming in Java into three steps: • Create the program by typing it into a text editor and saving it to a file named, say, My. Program. java. • Compile it by typing "javac My. Program. java" in the terminal window. • Run (or execute) it by typing "java My. Program" in the terminal window. • The first step creates the program; • The second translates it into a language more suitable for machine execution (and puts the result in a file named My. Program. class); • The third actually runs the program.

Engineered for Tomorrow Execution of Java program

Engineered for Tomorrow Execution of Java program

Engineered for Tomorrow First Simple Program public class Hello. World { public static void

Engineered for Tomorrow First Simple Program public class Hello. World { public static void main(String[] args) { System. out. println("Hello, World"); } } • keyword class to declare that a new class is being defined. • Hello. World is an identifier that is the name of the class. • The entire class definition, including all of its members, will be between the opening curly braces ({) and the closing curly braces (}).

Engineered for Tomorrow • All java program or application begin execution by calling the

Engineered for Tomorrow • All java program or application begin execution by calling the main() method. • The public keyword is an access specifier which allow the programmer to control the visibility of class members. • The “static” keyword allows main() to be called without having to instantiate a particular instance of the class. This is necessary so that main() is called by the java interpreter before any objects are made. • “void“, void is a return type, it just tell the compiler that main() does not return a value.

Engineered for Tomorrow • String args[] declares a parameter named args, which is an

Engineered for Tomorrow • String args[] declares a parameter named args, which is an array of instances of the class String (Array is collection of similar elements). • Object of type String store character strings. • args[] receives any command-line arguments information. • System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. • println() method displays the string which is passed to it.

Engineered for Tomorrow Second Simple Program class Addition { public static void main(String args[])

Engineered for Tomorrow Second Simple Program class Addition { public static void main(String args[]) { int a=5, b=10, c; c = a+b; System. out. println("n. Sum of two numbers: "+ c); } } Output: Sum of two numbers: 15

Engineered for Tomorrow Data Types, Variables, and Constants • For all data, assign a

Engineered for Tomorrow Data Types, Variables, and Constants • For all data, assign a name (identifier) and a data type • Data type tells compiler: ü How much memory to allocate ü Format in which to store data ü Types of operations you will perform on data • Compiler monitors use of data Java is a "strongly typed" language • Java "primitive data types" byte, short, int, long, float, double, char, boolean

Engineered for Tomorrow Integer Types - Whole Numbers Type Size Minimum Value Maximum. Value

Engineered for Tomorrow Integer Types - Whole Numbers Type Size Minimum Value Maximum. Value in Bytes byte 1 -128 127 short 2 -32, 768 32, 767 int 4 -2, 147, 483, 648 2, 147, 483, 647 long 8 -9, 223, 372, 036, 854, 775, 808 9, 223, 372, 036, 854, 775, 807 Example declarations: int test. Grade; int num. Players, high. Score, dice. Roll; short x. Coordinate, y. Coordinate; byte age. In. Years; long city. Population;

Engineered for Tomorrow Floating-Point Data Types • Numbers with fractional parts Type Size Minimum

Engineered for Tomorrow Floating-Point Data Types • Numbers with fractional parts Type Size Minimum Value Maximum Value in Bytes float 4 1. 4 E-45 3. 4028235 E 38 double 8 4. 9 E-324 1. 7976931348623157 E 308 Example declarations: float sales. Tax; double interest. Rate; double paycheck, sum. Salaries

Engineered for Tomorrow char Data Type • One Unicode character (16 bits - 2

Engineered for Tomorrow char Data Type • One Unicode character (16 bits - 2 bytes) Type Size Minimum Value Maximum Value in Bytes char 2 character encoded as 0 encoded as FFFF Example declarations: char final. Grade; char newline, tab, double. Quotes

Engineered for Tomorrow boolean Data Type • Two values only: true false • Used

Engineered for Tomorrow boolean Data Type • Two values only: true false • Used for decision making or as "flag" variables • Example declarations: boolean is. Empty; boolean passed, failed;

Engineered for Tomorrow Declaring Variables • Variables hold one value at a time, but

Engineered for Tomorrow Declaring Variables • Variables hold one value at a time, but that value can change • Syntax: data. Type identifier; or data. Type identifier 1, identifier 2, …; • Naming convention for variable names: ü First letter is lowercase ü Embedded words begin with uppercase letter

Engineered for Tomorrow Identifiers - symbolic names • Identifiers are used to name classes,

Engineered for Tomorrow Identifiers - symbolic names • Identifiers are used to name classes, variables, and methods. • Identifier Rules: ü Must start with a "Java letter" A - Z, a - z, _, $, and Unicode letters ü Can contain essentially any number of Java letters and digits, but no spaces ü Cannot be keywords or reserved words ü Names of variables should be meaningful and reflect the data they will store. ü Case sensitive!! Number 1 and number 1 are different!

Engineered for Tomorrow Assigning Values to Variables • Assignment operator = value; ü Value

Engineered for Tomorrow Assigning Values to Variables • Assignment operator = value; ü Value on the right of the operator is assigned to the variable on the left ü Value on the right can be a literal (text representing a specific value), another variable, or an expression (explained later) • Syntax: data. Type variable. Name = initial. Value; Or data. Type variable 1 = initial. Value 1, variable 2 = initial. Value 2, …;

Engineered for Tomorrow Literals • int, short, byte ü Optional initial sign (+ or

Engineered for Tomorrow Literals • int, short, byte ü Optional initial sign (+ or -) followed by digits 0 – 9 in any combination. • long ü Optional initial sign (+ or -) followed by digits 0– 9 in any combination, terminated with an L or l. ***Use the capital L because the lowercase l can be confused with the number 1.

Engineered for Tomorrow Floating-Point Literals • float ü Optional initial sign (+ or -)

Engineered for Tomorrow Floating-Point Literals • float ü Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format, terminated by an F or f. • double ü Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format. ü Commas, dollar signs, and percent signs (%) cannot be used in integer or floating-point literals

Engineered for Tomorrow char and boolean Literals • char ü Any printable character enclosed

Engineered for Tomorrow char and boolean Literals • char ü Any printable character enclosed in single quotes ü A decimal value from 0 – 65535 'm' , where m is an escape sequence. For example, 'n' represents a newline, and 't' represents a tab character. • boolean ü true or false

Engineered for Tomorrow String Literals • String is actually a class, not a basic

Engineered for Tomorrow String Literals • String is actually a class, not a basic data type; String variables are objects. • String literal: text contained within double quotes. • Example of String literals: "Hello" "Hello world" "The value of x is "

Engineered for Tomorrow String Concatenation Operator (+) • Combines String literals with other data

Engineered for Tomorrow String Concatenation Operator (+) • Combines String literals with other data types for printing. • Example: String hello = "Hello"; String there = "there"; String greeting = hello + ' ' + there; System. out. println( greeting ); Output is: Hello there

Engineered for Tomorrow Assigning the Values of Other Variables • Syntax: data. Type variable

Engineered for Tomorrow Assigning the Values of Other Variables • Syntax: data. Type variable 2 = variable 1; • Rules: 1. variable 1 needs to be defined before this statement appears in the source code. 2. variable 1 and variable 2 need to be compatible data types; in other words, the precision of variable 1 must be lower than or equal to that of variable 2.

Engineered for Tomorrow Compatible Data Types Any type in right column can be assigned

Engineered for Tomorrow Compatible Data Types Any type in right column can be assigned to type in left column: Data Type Compatible Data Types byte short byte, short int byte, short, int, char long byte, short, int, long, char float, byte, short, int, long, char double float, double, byte, short, int, long, char boolean char

Engineered for Tomorrow Sample Assignments • This is a valid assignment: float sales. Tax

Engineered for Tomorrow Sample Assignments • This is a valid assignment: float sales. Tax =. 05 f; double tax. Rate = sales. Tax; • This is invalid because the float data type is lower in precision than the double data type: double tax. Rate =. 05; float sales. Tax = tax. Rate;

Engineered for Tomorrow Arrays • An array is an ordered list of values Each

Engineered for Tomorrow Arrays • An array is an ordered list of values Each value has a numeric index The entire array has a single name 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 scores An array of size N is indexed from zero to N-1

Engineered for Tomorrow Arrays(Cont. . d) • A particular value in an array is

Engineered for Tomorrow Arrays(Cont. . d) • A particular value in an array is referenced using the array name followed by the index in brackets • For example, the expression scores[2] refers to the value 94 (the 3 rd value in the array) • That expression represents a place to store a single integer and can be used wherever an integer variable can be used

Engineered for Tomorrow Arrays(Cont. . d) • For example, an array element can be

Engineered for Tomorrow Arrays(Cont. . d) • For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System. out. println ("Top = " + scores[5]);

Engineered for Tomorrow Arrays(Cont. . d) • The values held in an array are

Engineered for Tomorrow Arrays(Cont. . d) • The values held in an array are called array elements • An array stores multiple values of the same type – the element type • The element type can be a primitive type or an object reference • Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. • In Java, the array itself is an object that must be instantiated

Engineered for Tomorrow Declaring and Creating Arrays • Declaring and Creating arrays Arrays are

Engineered for Tomorrow Declaring and Creating Arrays • Declaring and Creating arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[] = new int[ 12 ]; Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array We can create arrays of objects too String b[] = new String[ 100 ];

Engineered for Tomorrow Declaring Arrays • The scores array could be declared as follows:

Engineered for Tomorrow Declaring Arrays • The scores array could be declared as follows: int[] scores = new int[10]; • The type of the variable scores is int[] (an array of ints) • Note that the array type does not specify its size, but each object of that type has a specific size • The reference variable scores is set to a new array object that can hold 10 integers • An array is an object, therefore all the values are initialized to default ones (here 0)

Engineered for Tomorrow Declaring Arrays • Some other examples of array declarations: float[] prices

Engineered for Tomorrow Declaring Arrays • Some other examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

Engineered for Tomorrow Alternate Array Syntax • The brackets of the array type can

Engineered for Tomorrow Alternate Array Syntax • The brackets of the array type can be associated with the element type or with the name of the array • Therefore the following two declarations are equivalent: float[] prices; float prices[]; • The first format generally is more readable and should be used

Engineered for Tomorrow Initializer Lists • An initializer list can be used to instantiate

Engineered for Tomorrow Initializer Lists • An initializer list can be used to instantiate and fill an array in one step. • The values are delimited by braces and separated by commas • Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letter. Grades = {'A', 'B', 'C', 'D', ’F'};

Engineered for Tomorrow • Note that when an initializer list is used: the new

Engineered for Tomorrow • Note that when an initializer list is used: the new operator is not used no size value is specified • The size of the array is determined by the number of items in the initializer list • An initializer list can be used only in the array declaration

Engineered for Tomorrow Processing Array Elements • Often a for( ) loop is used

Engineered for Tomorrow Processing Array Elements • Often a for( ) loop is used to process each of the elements of the array in turn. for (int i = 0; i < NUM_STUDENTS; i++) { System. out. print(STUDENTS[i]+"t"+scores[i]+"t"); System. out. println(scores[i]-average); } • The loop control variable, i, is used as the index to access array components

Engineered for Tomorrow Array Parameters • Methods can accept arrays via parameters • Use

Engineered for Tomorrow Array Parameters • Methods can accept arrays via parameters • Use square brackets [ ] in the parameter declaration: public static double sum(double [] array) { for (int i=0; i < array. length; i++) . . . } • This works for any size array use the . length attribute of an array to control the for loop

Engineered for Tomorrow Two-Dimensional Arrays • A one-dimensional array stores a list of elements

Engineered for Tomorrow Two-Dimensional Arrays • A one-dimensional array stores a list of elements • A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions

Engineered for Tomorrow Two-Dimensional Arrays • To be precise, a two-dimensional array in Java

Engineered for Tomorrow Two-Dimensional Arrays • To be precise, a two-dimensional array in Java is an array of arrays • A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; • A two-dimensional array element is referenced using two index values value = scores[3][6] • The array stored in one row or column can be specified using one index

Engineered for Tomorrow Two-Dimensional Arrays • To initialize a two dimensional array you encapsulate

Engineered for Tomorrow Two-Dimensional Arrays • To initialize a two dimensional array you encapsulate each row in curly brackets, separating elements by commas. You separate each row by commas and put the entire array in curly brackets: int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; or… int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; • Another way to think of two dimensional arrays is that a two dimensional is a one dimensional array of one dimensional arrays. Said another way, it is a reference variable to an array that holds reference variables to arrays. This is apparent when using the length data member in two dimensional arrays: int[][] numbers = new int[3][4]; numbers. length – the number of rows numbers[0]. length – the number of columns in the first row Example: Two. Dim. Lengths. java

Engineered for Tomorrow Example Program class Matrix. Sum{ public static void main(String[] args) {

Engineered for Tomorrow Example Program class Matrix. Sum{ public static void main(String[] args) { int array[][]= {{4, 5, 6}, {6, 8, 9}} int array 1[][]= {{5, 4, 6}, {5, 6, 7}}; System. out. println("Number of Row= " + array. length); System. out. println("Number of Column= " + array[1]. length); int l= array. length; System. out. println("Matrix 1 : "); for(int i = 0; i < l; i++) { for(int j = 0; j <= l; j++) { System. out. print(" "+ array[i][j]); } System. out. println(); }

Engineered for Tomorrow int m= array 1. length; System. out. println("Matrix 2 : ");

Engineered for Tomorrow int m= array 1. length; System. out. println("Matrix 2 : "); for(int i = 0; i < m; i++) { for(int j = 0; j <= m; j++) { System. out. print(" "+array 1[i][j]); } System. out. println(); } System. out. println("Addition of both matrix : "); for(int i = 0; i < m; i++) { for(int j = 0; j <= m; j++) { System. out. print(" "+(array[i][j]+array 1[i][j])); } System. out. println(); } } }

Engineered for Tomorrow Type Casting • Java supports two types of castings – primitive

Engineered for Tomorrow Type Casting • Java supports two types of castings – primitive data type casting and reference type casting. • Reference type casting is nothing but assigning one Java object to another object. It comes with very strict rules and is explained clearly in Object Casting. • Java data type casting comes with 2 flavors. 1. Implicit casting 2. Explicit casting

Engineered for Tomorrow Implicit casting (widening conversion) • A data type of lower size

Engineered for Tomorrow Implicit casting (widening conversion) • A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is done implicitly by the JVM. The lower size is widened to higher size. This is also named as automatic type conversion. • Examples: int x = 10; // occupies 4 bytes double y = x; // occupies 8 bytes System. out. println(y); // prints 10. 0 • In the above code 4 bytes integer value is assigned to 8 bytes double value.

Engineered for Tomorrow Explicit casting (narrowing conversion) • A data type of higher size

Engineered for Tomorrow Explicit casting (narrowing conversion) • A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size. This is not done implicitly by the JVM and requires explicit casting; a casting operation to be performed by the programmer. The higher size is narrowed to lower size. double x = 10. 5; // 8 bytes int y = x; // 4 bytes ; raises compilation error • In the above code, 8 bytes double value is narrowed to 4 bytes int value. It raises error. Let us explicitly type cast it. double x = 10. 5; int y = (int) x; • The double x is explicitly converted to int y. The thumb rule is, on both sides, the same data type should exist.

Acceptable Implicit Casts char 16 bit byte 8 bit short 16 bit Illegal b

Acceptable Implicit Casts char 16 bit byte 8 bit short 16 bit Illegal b = l; l = f; c = s; int 32 bit long 64 bit OK l = b; i = c; f = l float 32 bit double 64 bit

Engineered for Tomorrow Expressions and Arithmetic Operators • Operators are special symbols used for:

Engineered for Tomorrow Expressions and Arithmetic Operators • Operators are special symbols used for: mathematical functions assignment statements logical comparisons • Examples of operators: 3 + 5 // uses + operator 14 + 5 – 4 * (5 – 3) // uses +, -, * operators • Expressions: can be combinations of variables and operators that result in a value • There are 5 different groups of operators: üArithmetic Operators üAssignment Operator üIncrement / Decrement Operators üRelational Operators üLogical Operators

Engineered for Tomorrow Java Arithmetic Operators • The following table summarizes the arithmetic operators

Engineered for Tomorrow Java Arithmetic Operators • The following table summarizes the arithmetic operators available in Java. This is an integer division where the fractional part is truncated.

Engineered for Tomorrow Simple Arithmetic Example > p q r s t > java

Engineered for Tomorrow Simple Arithmetic Example > p q r s t > java Example = 7 = 3 = 10 = 2 = 1

Engineered for Tomorrow Modulus v Generates the remainder when you divide two integer values.

Engineered for Tomorrow Modulus v Generates the remainder when you divide two integer values. • 5%3 gives 2 5%4 gives 1 • 5%5 gives 0 5%10 gives 5 v Modulus operator is most commonly used with integer operands. If we attempt to use the modulus operator on floating-point values we will garbage!

Engineered for Tomorrow Basic Assignment Operator • We assign a value to a variable

Engineered for Tomorrow Basic Assignment Operator • We assign a value to a variable using the basic assignment operator (=). • Assignment operator stores a value in memory. • The syntax is left. Side = right. Side ; Allways it is a variable identifier. Examples: i = 1; start = i; sum = first. Number + second. Number; avg = (one + two + three) / 3;

Engineered for Tomorrow The Right Side of the Assignment Operator • The Java assignment

Engineered for Tomorrow The Right Side of the Assignment Operator • The Java assignment operator assigns the value on the right side of the operator to the variable appearing on the left side of the operator. • The right side may be either: Literal: ex. i = 1; Variable identifier: ex. start = i; Expression: ex. sum = first + second;

Engineered for Tomorrow Shorthand Operators Java allows combining arithmetic and assignment operators into a

Engineered for Tomorrow Shorthand Operators Java allows combining arithmetic and assignment operators into a single operator: Addition/assignment Subtraction/assignment Multiplication/assignment Division/assignment Remainder/assignment += = = /= %=

Engineered for Tomorrow Shorthand Operators Example public class Example { public static void main(String[]

Engineered for Tomorrow Shorthand Operators Example public class Example { public static void main(String[] args) { int j, p, q, r, s, t; j = 5; p = 1; q = 2; r = 3; s = 4; t = 5; p += j; q -= j; r *= j; s /= j; t %= j; System. out. println("p = " + p); System. out. println("q = " + q); System. out. println("r = " + r); System. out. println("s = " + s); System. out. println("t = " + t); > java Example } p = 6 } q = -3 r = 15 s = 0 t = 0 >

Engineered for Tomorrow • The syntax is left. Side Allways it is a variable

Engineered for Tomorrow • The syntax is left. Side Allways it is a variable identifier. Op= right. Side ; It is an arithmetic operator. • This is equivalent to: left. Side = left. Side Op right. Side ; • x%=5; x = x % 5; • x*=y+w*z; x = x*(y+w*z); It is either a literal | a variable identifier | an expression.

Engineered for Tomorrow Assigning Literals • In this case, the literal is stored in

Engineered for Tomorrow Assigning Literals • In this case, the literal is stored in the space memory allocated for the variable at the left side. A. Variables are allocated in memory. A int first. Number=1, second. Number; first. Number = 234; B second. Number = 87; Code Introduction to OOP first. Number second. Number 1 ? ? ? B. Literals are assigned to variables. first. Number second. Number Dr. S. GANNOUNI & Dr. A. TOUIR 234 87 State of Memory Page 86

Assigning Variables Engineered for Tomorrow • In this case, the value of the variable

Assigning Variables Engineered for Tomorrow • In this case, the value of the variable at the right side is stored in the space memory allocated for the variable at the left side. A. Variables are allocated in memory. first. Number i A int first. Number=1, i; first. Number = 234; i = first. Number; Code Introduction to OOP B 1 ? ? ? B. values are assigned to variables. first. Number i Dr. S. GANNOUNI & Dr. A. TOUIR 234 State of Memory Page 87

Engineered for Tomorrow Assigning Expressions • In this case, the result of the evaluation

Engineered for Tomorrow Assigning Expressions • In this case, the result of the evaluation of the expression is stored in the space memory allocated for variable at the left side. A. Variables are allocated in memory. A int first, second, sum; first = 234; second = 87; Sum = first + second Code Introduction to OOP B first 1 sum ? ? ? second 87 B. Values are assigned to variables. first 234 sum 321 Dr. S. GANNOUNI & Dr. A. TOUIR State of Memory Page 88

Engineered for Tomorrow Relational Operators > < >= <= == != Primitives or Object

Engineered for Tomorrow Relational Operators > < >= <= == != Primitives or Object References • Equal (Equivalent) == • Not Equal != The Result is Always true or false

Engineered for Tomorrow public class Example public static void int p =2; int q

Engineered for Tomorrow public class Example public static void int p =2; int q Integer i = new Integer j = new { main(String[] args) { = 2; int r = 3; Integer(10); System. out. println("p } } < r " + (p < r)); > r " + (p > r)); == q " + (p == q)); != q " + (p != q)); System. out. println("i == j " + (i == j)); System. out. println("i != j " + (i != j)); > p p i i java Example < r true > r false == q true != q false == j false != j true

Engineered for Tomorrow Logical Operators (boolean) && || !

Engineered for Tomorrow Logical Operators (boolean) && || !

Engineered for Tomorrow Logical (&&) Operator Examples > f f t t > java

Engineered for Tomorrow Logical (&&) Operator Examples > f f t t > java && f && t Example false true

Engineered for Tomorrow Logical (||) Operator Examples > f f t t > java

Engineered for Tomorrow Logical (||) Operator Examples > f f t t > java || f || t Example false true

Engineered for Tomorrow Logical (!) Operator Examples > java Example !f true !t false

Engineered for Tomorrow Logical (!) Operator Examples > java Example !f true !t false >

Engineered for Tomorrow Logical Operators (Bit Level) & • • AND OR XOR NOT

Engineered for Tomorrow Logical Operators (Bit Level) & • • AND OR XOR NOT | ^ ~ & | ^ ~

Engineered for Tomorrow Logical Operators (Bit Level) & | ^ ~ int a =

Engineered for Tomorrow Logical Operators (Bit Level) & | ^ ~ int a = 10; // 00001010 = 10 int b = 12; // 00001100 = 12 & a b a & b 000000000000001010 000000000000001100 000000000000001000 10 12 8 | a b a | b 000000000000001010 000000000000001100 000000000000001110 10 12 14 ^ a b a ^ b 000000000000001010 000000000000001100 000000000000000110 10 12 6 a ~a 000000000000001010 111111111111110101 10 -11 AND OR XOR ~ NOT

Engineered for Tomorrow Logical (bit) Operator Examples > java Example and 8 or 14

Engineered for Tomorrow Logical (bit) Operator Examples > java Example and 8 or 14 xor 6 na -11 >

Engineered for Tomorrow Shift Operators (Bit Level) << >> >>> • Shift Left •

Engineered for Tomorrow Shift Operators (Bit Level) << >> >>> • Shift Left • Shift Right >> Based on Sign • Shift Right >>> Fill with Zeros << Fill with Zeros

Engineered for Tomorrow Shift Operators << >> int a = 3; //. . .

Engineered for Tomorrow Shift Operators << >> int a = 3; //. . . 00000011 = 3 int b = -4; //. . . 11111100 = -4 << Left >> Right a a << 2 0000000000000001100 3 12 b b << 2 1111111111111110000 -4 -16 a a >> 2 00000000000000011 0000000000000000 3 0 b b >> 2 11111111111111100 1111111111111111 -4 -1

Engineered for Tomorrow Shift Operator >>> int a = 3; //. . . 00000011

Engineered for Tomorrow Shift Operator >>> int a = 3; //. . . 00000011 = 3 int b = -4; //. . . 11111100 = -4 >>> Right 0 a 00000000000000011 a >>> 2 0000000000000000 3 0 b 11111111111111100 b >>> 2 00111111111111111 -4 +big

Engineered for Tomorrow Shift Operator Examples > java Example a<<2 = 12 b<<2 =

Engineered for Tomorrow Shift Operator Examples > java Example a<<2 = 12 b<<2 = -16 a>>2 = 0 b>>2 = -1 a>>>2 = 0 b>>>2 = 1073741823 >

Engineered for Tomorrow Ternary Operator ? : Any expression that evaluates to a boolean

Engineered for Tomorrow Ternary Operator ? : Any expression that evaluates to a boolean value. boolean_expression ? expression_1 If true this expression is evaluated and becomes the value entire expression. : expression_2 If false this expression is evaluated and becomes the value entire expression.

Engineered for Tomorrow Ternary ( ? : ) Operator Examples > java Example t?

Engineered for Tomorrow Ternary ( ? : ) Operator Examples > java Example t? true: false true t? 1: 2 1 f? true: false f? 1: 2 2 >

Engineered for Tomorrow Operators Precedence

Engineered for Tomorrow Operators Precedence

Engineered for Tomorrow Java Control Statements • Java Control statements control the order of

Engineered for Tomorrow Java Control Statements • Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements; • Selection statements: if, if-else and switch. • Loop statements: while, do-while and for. • Transfer statements: break, continue, return, try-catch-finally and assert. • We use control statements when we want to change the default sequential order of execution

Engineered for Tomorrow The if statement • The if statement executes a block of

Engineered for Tomorrow The if statement • The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. • You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression. • The simple if statement has the following syntax: if (<conditional expression>) <statement action>

Engineered for Tomorrow Example Program public class If. Statement. Demo { public static void

Engineered for Tomorrow Example Program public class If. Statement. Demo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) System. out. println("a > b"); if (a < b) System. out. println("b > a"); } }

Engineered for Tomorrow The If-else Statement • The if/else statement is an extension of

Engineered for Tomorrow The If-else Statement • The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. • You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression. • The if-else statement has the following syntax: if (<conditional expression>) <statement action> else <statement action>

Engineered for Tomorrow Example Program public class If. Else. Statement. Demo { public static

Engineered for Tomorrow Example Program public class If. Else. Statement. Demo { public static void main(String[] args) { int a = 10, b = 20; if(a > b) { System. out. println("a > b"); } else { System. out. println("b > a"); } } }

Engineered for Tomorrow Common Forms of the if Statement The examples in the book

Engineered for Tomorrow Common Forms of the if Statement The examples in the book use the if statement in the following forms: Single line if statement Multiline if statement with curly braces if (condition) statement if (condition) { statement. . . more statements. . . } if/else statement with curly braces if (condition) { statementstrue } else { statementsfalse } Cascading if statement if (condition 1) { statements 1 } else if (condition 2) { statements 2. . . more else/if conditions. . . } else { statementselse }

Engineered for Tomorrow Switch Statement • The switch statement provides another way to decide

Engineered for Tomorrow Switch Statement • The switch statement provides another way to decide which statement to execute next • The switch statement evaluates an expression, then attempts to match the result to one of several possible cases • Each case contains one value (a constant) and a list of statements • The flow of control transfers to statement associated with the first case value that matches.

Engineered for Tomorrow Syntax of Switch • The general syntax of a switch statement

Engineered for Tomorrow Syntax of Switch • The general syntax of a switch statement is: switch and case are reserved words switch ( expression ) { case value 1 : statement-list 1 case value 2 : statement-list 2 case value 3 : statement-list 3 case. . . } If expression matches value 2, control jumps to here

Engineered for Tomorrow Switch Statement • Often a break statement is used as the

Engineered for Tomorrow Switch Statement • Often a break statement is used as the last statement in each case's statement list • A break statement causes control to transfer to the end of the switch statement • If a break statement is not used, the flow of control will continue into the next case • Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

Engineered for Tomorrow • A switch statement can have an optional default case •

Engineered for Tomorrow • A switch statement can have an optional default case • The default case has no associated value and simply uses the reserved word default • If the default case is present, control will transfer to it if no other case value matches • If there is no default case, and no other value matches, control falls through to the statement after the switch

Engineered for Tomorrow • The expression of a switch statement must result in an

Engineered for Tomorrow • The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int, long) or a char • It cannot be a boolean value or a floating point value (float or double) • The implicit boolean condition in a switch statement is equality • You cannot perform relational checks with a switch statement

Engineered for Tomorrow Example Program import java. io. *; public class Switch. Example{ public

Engineered for Tomorrow Example Program import java. io. *; public class Switch. Example{ public static void main(String[] args) { int x=10, y=20; Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); System. out. println("1. Add“, 2. Subtract, 3. Multiply, 4. Divide”); System. out. println("enter your choice: "); int a= Integer. parse. Int(br. read. Line());

Engineered for Tomorrow switch (a) { case 1: System. out. println(“Sum is" + (x+y));

Engineered for Tomorrow switch (a) { case 1: System. out. println(“Sum is" + (x+y)); break; case 2: System. out. println(“ Difference is=" + (x-y)); break; case 3: System. out. println(“Multiplication is="+ (x*y)); break; case 4: System. out. println(“Division is="+ (x/y)); break; default: System. out. println("Invalid Entry!: "); }

Engineered for Tomorrow Loop Statements • Java has three types of loop statements: the

Engineered for Tomorrow Loop Statements • Java has three types of loop statements: the while, do-while, and for statements. • Most branching and looping statements are controlled by Boolean expressions • A Boolean expression evaluates to either true or false • The primitive type boolean may only take the values true or false. • Loops in Java are similar to those in other high-level languages. • The code that is repeated in a loop is called the body of the loop. Each repetition of the loop body is called an iteration of the loop

Engineered for Tomorrow while statement • A while statement is used to repeat a

Engineered for Tomorrow while statement • A while statement is used to repeat a portion of code (i. e. , the loop body) based on the evaluation of a Boolean expression • The Boolean expression is checked before the loop body is executed. When it is false, the loop body is not executed at all. • Before the execution of each following iteration of the loop body, the Boolean expression is checked again üIf true, the loop body is executed again üIf false, the loop statement ends The loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ({ })

Engineered for Tomorrow while Syntax while (Boolean_Expression) Statement Or while (Boolean_Expression) { Statement_1 Statement_2

Engineered for Tomorrow while Syntax while (Boolean_Expression) Statement Or while (Boolean_Expression) { Statement_1 Statement_2 Statement_Last }

Engineered for Tomorrow do-while Statement • A do-while statement is used to execute a

Engineered for Tomorrow do-while Statement • A do-while statement is used to execute a portion of code (i. e. , the loop body), and then repeat it based on the evaluation of a Boolean expression • The loop body is executed at least once üThe Boolean expression is checked after the loop body is executed üThe Boolean expression is checked after each iteration of the loop body üIf true, the loop body is executed again üIf false, the loop statement ends üDon't forget to put a semicolon after the Boolean expression. • Like the while statement, the loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ({ })

Engineered for Tomorrow do-while Syntax do Statement while (Boolean_Expression); Or do { Statement_1 Statement_2

Engineered for Tomorrow do-while Syntax do Statement while (Boolean_Expression); Or do { Statement_1 Statement_2 } Statement_Last while (Boolean_Expression);

Engineered for Tomorrow The for Statement • The for statement is most commonly used

Engineered for Tomorrow The for Statement • The for statement is most commonly used to step through an integer variable in equal increments • It begins with the keyword for, followed by three expressions in parentheses that describe what to do with one or more controlling variables • The first expression tells how the control variable or variables are initialized or declared and initialized before the first iteration • The second expression determines when the loop should end, based on the evaluation of a Boolean expression before each iteration • The third expression tells how the control variable or variables are updated after each iteration of the loop body

Engineered for Tomorrow The for Statement Syntax for (Initializing; Boolean_Expression; Update) Body • The

Engineered for Tomorrow The for Statement Syntax for (Initializing; Boolean_Expression; Update) Body • The Body may consist of a single statement or a list of statements enclosed in a pair of braces ({ }) • Note that the three control expressions are separated by two, not three, semicolons • Note that there is no semicolon after the closing parenthesis at the beginning of the loop

Engineered for Tomorrow Semantics of the for Statement

Engineered for Tomorrow Semantics of the for Statement

Engineered for Tomorrow for Statement Syntax and Alternate Semantics

Engineered for Tomorrow for Statement Syntax and Alternate Semantics

Engineered for Tomorrow for Statement Syntax and Alternate Semantics

Engineered for Tomorrow for Statement Syntax and Alternate Semantics

Engineered for Tomorrow For-each Loop • The basic for loop was extended in Java

Engineered for Tomorrow For-each Loop • The basic for loop was extended in Java 5 to make iteration over arrays and other collections more convenient. This newer for statement is called the enhanced for or for-each. • The for-each loop is used to access each successive value in a collection of values. • General Form • For-each loop for (type var : arr) { body-of-loop } Equivalent for loop for (int i = 0; i < arr. length; i++) { type var = arr[i]; body-of-loop }

Engineered for Tomorrow Example - Adding all elements of an array double[] ar =

Engineered for Tomorrow Example - Adding all elements of an array double[] ar = {1. 2, 3. 0, 0. 8}; int sum = 0; for (double d : ar) { // d gets successively each value in ar. sum += d; } Output: 5. 0

Engineered for Tomorrow Nested Loops • Loops can be nested, just like other Java

Engineered for Tomorrow Nested Loops • Loops can be nested, just like other Java structures When nested, the inner loop iterates from beginning to end for each single iteration of the outer loop int row. Num, column. Num; for (row. Num = 1; row. Num <=3; row. Num++) { for (column. Num = 1; column. Num <=2; column. Num++) System. out. print(" row " + row. Num + " column " + column. Num); System. out. println(); }

Engineered for Tomorrow The break and continue Statements • The break statement consists of

Engineered for Tomorrow The break and continue Statements • The break statement consists of the keyword break followed by a semicolon. • When executed, the break statement ends the nearest enclosing switch or loop statement • The continue statement consists of the keyword continue followed by a semicolon. • When executed, the continue statement ends the current loop body iteration of the nearest enclosing loop statement Note that in a for loop, the continue statement transfers control to the update expression • When loop statements are nested, remember that any break or continue statement applies to the innermost, containing loop statement

Engineered for Tomorrow The Labeled break Statement • There is a type of break

Engineered for Tomorrow The Labeled break Statement • There is a type of break statement that, when used in nested loops, can end any containing loop, not just the innermost loop • If an enclosing loop statement is labeled with an Identifier, then the following version of the break statement will exit the labeled loop, even if it is not the innermost enclosing loop: break some. Identifier; • To label a loop, simply precede it with an Identifier and a colon: some. Identifier:

Engineered for Tomorrow Thank You

Engineered for Tomorrow Thank You