SlideShare a Scribd company logo
OBJECT ORIENTED PROGRAMMING
INDEX  UNIT 2 PPT SLIDES S.NO.  TOPIC  LECTURE NO.  PPTSLIDES History of Java,     L1 L1.1TO L1.20  Java buzzwords, data types .   variables, scope and life time of variables,  L2 L2.1 TO L2.20 arrays, operators, expressions control statements,    L3  L3.1 TO L3.9 type conversion and costing simple java program,  L 4  L4.1 TO L4.8 classes and objects – concepts of classes   objects, constructors, methods  L5 L5.1 TO 5.6 Access control, this keyword,  L6  L6.1 TO 6.8 garbage collection 7 overloading methods and constructors,  L7 L7.1 TO 7.6 parameter passing  8 R ecursion, string handling.  L8  L 8.1 TO 8.6
Java History Computer language innovation and development occurs for two fundamental reasons: 1) to adapt to changing environments and uses 2) to implement improvements in the art of programming The development of Java was driven by both in equal measures. Many Java features are inherited from the earlier languages: B    C    C++    Java
Before Java: C Designed by Dennis Ritchie in 1970s. Before C: BASIC, COBOL, FORTRAN, PASCAL  C- structured, efficient, high-level language that could replace assembly code when creating systems programs. Designed, implemented and tested by programmers.
Before Java: C++ Designed by Bjarne Stroustrup in 1979. Response to the increased complexity of programs and respective improvements in the programming paradigms and methods: 1) assembler languages 2) high-level languages 3) structured programming 4) object-oriented programming (OOP) OOP – methodology that helps organize complex programs through the use of inheritance, encapsulation and polymorphism. C++ extends C by adding object-oriented features.
Java: History In 1990, Sun Microsystems started a project called Green. Objective: to develop software for consumer electronics. Project was assigned to James Gosling, a veteran of classic network software design. Others included Patrick Naughton, ChrisWarth, Ed Frank, and Mike Sheridan. The team started writing programs in C++ for embedding into –  toasters –  washing machines –  VCR’s Aim was to make these appliances more “intelligent”.
Java: History (contd.) C++ is powerful, but also dangerous. The power and popularity of C derived from the extensive use of pointers. However, any incorrect use of pointers can cause memory leaks, leading the program to crash. In a complex program, such memory leaks are often hard to detect. Robustness is essential. Users have come to expect that Windows may crash or that a program running under Windows may crash. (“This program has performed an illegal operation and will be shut down”) However, users do not expect toasters to crash, or washing machines to crash. A design for consumer electronics has to be  robust .  Replacing pointers by references, and automating memory management was the proposed solution.
Java: History (contd.) Hence, the team built a new programming language called Oak, which  avoided potentially dangerous constructs in C++, such as pointers, pointer arithmetic, operator overloading etc. Introduced automatic memory management, freeing the programmer to concentrate on other things. Architecture neutrality (Platform independence) Many different CPU’s are used as controllers. Hardware chips are evolving rapidly. As better chips become available, older chips become obsolete and their production is stopped. Manufacturers of toasters and washing machines would like to use the chips available off the shelf, and would not like to reinvest in compiler development every two-three years. So, the software and programming language had to be  architecture neutral .
Java: History (contd) It was soon realized that these design goals of consumer electronics perfectly suited an ideal programming language for the Internet and WWW, which should be:  object-oriented (& support GUI) –  robust –  architecture neutral Internet programming presented a BIG business opportunity. Much bigger than programming for consumer electronics. Java was “re-targeted” for the Internet The team was expanded to include Bill Joy (developer of Unix), Arthur van Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc. In 1994, an early web browser called WebRunner was written in Oak. WebRunner was later renamed HotJava. In 1995, Oak was renamed Java. A common story is that the name Java relates to the place from where the development team got its coffee. The name Java survived the trade mark search.
Java History Designed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan at Sun Microsystems in 1991. The original motivation is not Internet: platform-independent software embedded in consumer electronics devices. With Internet, the urgent need appeared to break the fortified positions of Intel, Macintosh and Unix programmer communities. Java as an “Internet version of C++”? No. Java was not designed to replace C++, but to solve a different set of problems.
The Java Buzzwords The key considerations were summed up by the Java team in the following list of buzzwords: Simple Secure Portable Object-oriented Robust Multithreaded Architecture-neutral Interpreted High performance Distributed Dynamic
simple  – Java is designed to be easy for the professional programmer to learn and use. object-oriented:  a clean, usable, pragmatic approach to objects, not restricted by the need for compatibility with other languages. Robust:  restricts the programmer to find the mistakes early, performs compile-time (strong typing) and run-time (exception-handling) checks, manages memory automatically. Multithreaded:  supports multi-threaded programming for writing program that perform concurrent computations
Architecture-neutral:  Java Virtual Machine provides a platform independent environment for the execution of Java byte code Interpreted and high-performance:  Java programs are compiled into an intermediate representation – byte code: a) can be later interpreted by any JVM b) can be also translated into the native machine code for efficiency.
Distributed:  Java handles TCP/IP protocols, accessing a resource through its URL much like accessing a local file. Dynamic:  substantial amounts of run-time type information to verify and resolve access to objects at run-time. Secure:  programs are confined to the Java execution environment and cannot access other parts of the computer.
Portability:  Many types of computers and operating systems are in use throughout the world—and many are connected to the Internet.  For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed. The same mechanism that helps ensure security also helps create portability. Indeed, Java's solution to these two problems is both elegant and efficient.
Data Types Java defines eight simple types: 1)byte – 8-bit integer type 2)short – 16-bit integer type 3)int – 32-bit integer type 4)long – 64-bit integer type 5)float – 32-bit floating-point type 6)double – 64-bit floating-point type 7)char – symbols in a character set 8)boolean – logical values true and false
byte: 8-bit integer type. Range: -128 to 127. Example: byte b = -15; Usage: particularly when working with data streams. short: 16-bit integer type. Range: -32768 to 32767. Example: short c = 1000; Usage: probably the least used simple type.
int:  32-bit integer type. Range: -2147483648 to 2147483647. Example: int b = -50000; Usage: 1) Most common integer type. 2) Typically used to control loops and to index arrays. 3) Expressions involving the byte, short and int values are promoted to int before calculation.
long:  64-bit integer type. Range: -9223372036854775808 to    9223372036854775807. Example: long l = 10000000000000000; Usage: 1) useful when int type is not large enough to hold the desired value float:  32-bit floating-point number. Range: 1.4e-045 to 3.4e+038. Example: float f = 1.5; Usage: 1) fractional part is needed 2) large degree of precision is not required
double:  64-bit floating-point number. Range: 4.9e-324 to 1.8e+308. Example: double pi = 3.1416; Usage: 1) accuracy over many iterative calculations 2) manipulation of large-valued numbers
char:  16-bit data type used to store characters. Range: 0 to 65536. Example:  char c = ‘a’; Usage: 1) Represents both ASCII and Unicode character sets; Unicode defines a character set with characters found in (almost) all human languages. 2) Not the same as in C/C++ where char is 8-bit and represents ASCII only.
boolean:  Two-valued type of logical values. Range: values true and false. Example: boolean b = (1<2); Usage: 1) returned by relational operators, such as 1<2 2) required by branching expressions such as if or for
Variables declaration – how to assign a type to a variable initialization – how to give an initial value to a variable scope – how the variable is visible to other parts of the program lifetime – how the variable is created, used and destroyed type conversion – how Java handles automatic type conversion type casting – how the type of a variable can be narrowed down type promotion – how the type of a variable can be expanded
Variables Java uses variables to store data. To allocate memory space for a variable JVM requires: 1) to specify the data type of the variable 2) to associate an identifier with the variable 3) optionally, the variable may be assigned an initial value All done as part of variable declaration.
Basic Variable Declaration datatype identifier [=value]; datatype must be A simple datatype User defined datatype (class type) Identifier is a recognizable name confirm to identifier rules Value is an optional initial value.
Variable Declaration We can declare several variables at the same time: type identifier [=value][, identifier [=value] …]; Examples: int a, b, c; int d = 3, e, f = 5; byte g = 22; double pi = 3.14159; char ch = 'x';
Variable Scope Scope determines the visibility of program elements with respect to other program elements. In Java, scope is defined separately for classes and methods: 1) variables defined by a class have a global scope 2) variables defined by a method have a local scope A scope is defined by a block: { … } A variable declared inside the scope is not visible outside: { int n; } n = 1;// this is illegal
Variable Lifetime Variables are created when their scope is entered by control flow and destroyed when their scope is left: A variable declared in a method will not hold its value between different invocations of this method. A variable declared in a block looses its value when the block is left. Initialized in a block, a variable will be re-initialized with every re-entry. Variables lifetime is confined to its scope!
Arrays An array is a group of liked-typed variables referred to by a common name, with individual variables accessed by their index. Arrays are: 1) declared 2) created 3) initialized 4) used Also, arrays can have one or several dimensions.
Array Declaration Array declaration involves: 1) declaring an array identifier 2) declaring the number of dimensions 3) declaring the data type of the array elements Two styles of array declaration: type array-variable[]; or type [] array-variable;
Array Creation After declaration, no array actually exists. In order to create an array, we use the new operator: type array-variable[]; array-variable = new type[size]; This creates a new array to hold size elements of type type, which reference will be kept in the variable array-variable.
Array Indexing Later we can refer to the elements of this array through their indexes: array-variable[index] The array index always starts with zero! The Java run-time system makes sure that all array indexes are in the correct range, otherwise raises a run-time error.
Array Initialization Arrays can be initialized when they are declared: int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31}; Note: 1) there is no need to use the new operator 2) the array is created large enough to hold all specified elements
Multidimensional Arrays Multidimensional arrays are arrays of arrays: 1) declaration:  int array[][]; 2) creation:  int array = new int[2][3]; 3) initialization int array[][] = { {1, 2, 3}, {4, 5, 6} };
Operators Types Java operators are used to build value expressions. Java provides a rich set of operators: 1) assignment 2) arithmetic 3) relational 4) logical 5) bitwise
Arithmetic assignments v = v % expr ; v %= expr; %= v = v / expr ; v /= expr; /= v = v * expr ; v *= expr; *= v = v - expr ; v -=expr; -= v = v + expr ; v += expr; +=
Basic Arithmetic Operators REMAINDER op1 % op2 % DIVISION op1 / op2 / MULTIPLY op1 * op2 * SUBSTRACT op1 - op2 - ADD op1 + op2 +
Relational operator Apply to numerical type Less than or equal <= Apply to numerical type Greater than or equal  >= Apply to numerical type Less than < Apply to numerical type Greater than > Apply to any type Not equals to != Apply to any type Equals to ==
Logical operators Logical XOR op1 ^ op2 ^ Logical NOT ! op ! Short-circuit OR op1 || op2 || Short-circuit AND op1 && op2 && Logical OR op1 | op2 | Logical AND op1 & op2 &
Bit wise operators Shifts all bits in op1 left by the value of op2 op1 << op2 << Shifts all bits in op1 right by the value of op2 op1 >> op2 >> Produces 1 bit if exactly one operand is 1 op1 ^ op2 ^ Produces 1 bit if either operand is 1 op1 |op2 | Produces 1 bit if both operands are 1 op1 & op2 & Inverts all bits ~op ~
An  expression  is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.  Examples of expressions are in bold below:  int  number = 0 ; anArray[0] = 100 ;  System.out.println ( &quot;Element 1 at index 0: &quot; + anArray[0] ); int  result = 1 + 2 ; // result is now 3 if( value1 == value2 ) System.out.println( &quot;value1 == value2&quot; );  Expressions
Expressions The data type of the value returned by an expression depends on the elements used in the expression. The expression number = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, number is an int.  As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String.  The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression:  1 * 2 * 3
Control Statements Java control statements cause the flow of execution to advance and branch based on the changes to the state of the program. Control statements are divided into three groups: 1) selection statements allow the program to choose different parts of the execution based on the outcome of an expression 2) iteration statements enable program execution to repeat one or more statements 3) jump statements enable your program to execute in a non-linear fashion
Selection Statements Java selection statements allow to control the flow of program’s execution based upon conditions known only during run-time. Java provides four selection statements: 1) if 2) if-else 3) if-else-if 4) switch
Iteration Statements Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true. Java provides three iteration statements: 1) while 2) do-while 3) for
Jump Statements Java jump statements enable transfer of control to other parts of program. Java provides three jump statements: 1) break 2) continue 3) return In addition, Java supports exception handling that can also alter the control flow of a program.
Type Conversion Size Direction of Data Type  Widening Type Conversion (Casting down) Smaller Data Type    Larger Data Type  Narrowing Type Conversion (Casting up) Larger Data Type    Smaller Data Type Conversion done in two ways  Implicit type conversion Carried out by compiler automatically  Explicit type conversion  Carried out by programmer using casting
Type Conversion Widening Type Converstion  Implicit conversion by compiler automatically  byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double float -> double
Type Conversion Narrowing Type Conversion Programmer should describe the conversion explicitly byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long double -> byte, short, char, int, long, float
Type Conversion byte and short are always promoted to int if one operand is long, the whole expression is promoted to long if one operand is float, the entire expression is promoted to float if any operand is double, the result is double
Type Casting General form:  (targetType) value Examples: 1) integer value will be reduced module  bytes range: int i; byte b = (byte) i; 2) floating-point value will be truncated to integer value: float f; int i = (int) f;
Simple Java Program A class to display a simple message: class MyProgram  { public static void main(String[] args)   { System.out.println(“First Java program.&quot;); } }
What is an Object? Real world objects are things that have: 1) state 2) behavior Example: your dog: state – name, color, breed, sits?, barks?, wages tail?, runs? behavior – sitting, barking, waging tail, running A software object is a bundle of variables (state) and methods (operations).
What is a Class? A class is a blueprint that defines the variables and methods common to all objects of a certain kind. Example: ‘your dog’ is a object of the class Dog. An object holds values for the variables defines in the class. An object is called an instance of the Class
Object Creation A variable is declared to refer to the objects of type/class String: String s; The value of s is null; it does not yet refer to any object. A new String object is created in memory with initial “abc” value: String s = new String(“abc”); Now s contains the address of this new object.
Object Destruction A program accumulates memory through its execution. Two mechanism to free memory that is no longer need by the program: 1) manual – done in C/C++ 2) automatic – done in Java In Java, when an object is no longer accessible through any variable, it is eventually removed from the memory by the garbage collector. Garbage collector is parts of the Java Run-Time Environment.
Class A basis for the Java language. Each concept we wish to describe in Java must be included inside a class. A class defines a new data type, whose values are objects: A class is a template for objects An object is an instance of a class
Class Definition A class contains a name, several variable declarations (instance variables) and several method declarations. All are called members of the class. General form of a class: class classname { type instance-variable-1; … type instance-variable-n; type method-name-1(parameter-list) { … } type method-name-2(parameter-list) { … } … type method-name-m(parameter-list) { … } }
Example: Class Usage class Box { double width; double height; double depth; } class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println (&quot;Volume is &quot; + vol); }  }
Constructor A constructor initializes the instance variables of an object. It is called immediately after the object is created but before the new operator completes. 1) it is syntactically similar to a method: 2) it has the same name as the name of its class 3) it is written without return type; the default  return type of a class constructor is the same class When the class has no constructor, the default constructor automatically initializes all its instance variables with zero.
Example: Constructor  class Box { double width; double height; double depth; Box() { System.out.println(&quot;Constructing Box&quot;); width = 10; height = 10; depth = 10; } double volume() { return width * height * depth; } }
Parameterized Constructor  class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { return width * height * depth;  } }
Methods General form of a method definition: type name(parameter-list) { …  return value;   …   } Components: 1) type - type of values returned by the method. If a method does not return any value, its return type must be void. 2) name is the name of the method 3) parameter-list is a sequence of type-identifier lists separated by commas 4) return value indicates what value is returned by the method.
Example: Method  Classes declare methods to hide their internal data structures, as well as for their own internal use: Within a class, we can refer directly to its member variables: class Box { double width, height, depth; void volume() { System.out.print(&quot;Volume is &quot;); System.out.println(width * height * depth); } }
Parameterized Method Parameters increase generality and applicability of a method: 1) method without parameters int square() { return 10*10; } 2) method with parameters int square(int i) { return i*i; } Parameter: a variable receiving value at the time the method is invoked. Argument: a value passed to the method when it is invoked.
Access Control: Data Hiding and Encapsulation Java provides control over the  visibility  of variables and methods. Encapsulation,  safely sealing data within the  capsule  of the class Prevents programmers from relying on details of class implementation, so you can update without worry Helps in protecting against accidental or wrong usage. Keeps code elegant and clean (easier to maintain)
Access Modifiers: Public, Private, Protected Public:  keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. Default(No visibility modifier is specified): it behaves like public in its package and private in other packages. Default Public  keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible.
Private  fields or methods for a class only visible within that class. Private members are  not  visible within subclasses, and are  not  inherited. Protected  members of a class are visible within the class, subclasses and  also  within all classes that are in the same package as that class.
Visibility public class Circle { private double x,y,r; // Constructor public Circle (double x, double y, double r) { this.x = x; this.y = y; this.r = r; } //Methods to return circumference and area public double circumference() { return 2*3.14*r;} public double area() { return 3.14 * r * r; }   }
Keyword this Can be used by any object to refer to itself in any class method Typically used to Avoid variable name collisions Pass the receiver as an argument Chain constructors
Keyword this Keyword this allows a method to refer to the object that invoked it. It can be used inside any method to refer to the current object: Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }
Garbage Collection Garbage collection is a mechanism to remove objects from memory when they are no longer needed. Garbage collection is carried out by the garbage collector: 1) The garbage collector keeps track of how many references an object has. 2) It removes an object from memory when it has no longer any references. 3) Thereafter, the memory occupied by the object can be allocated again. 4) The garbage collector invokes the finalize method.
finalize() Method A constructor helps to initialize an object just after it has been created. In contrast, the finalize method is invoked just before the object is destroyed: 1) implemented inside a class as: protected void finalize() { … } 2) implemented when the usual way of removing objects from memory is insufficient, and some special actions has to be carried out
Method Overloading It is legal for a class to have two or more methods with the same name. However, Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments. Therefore the same-named methods must be distinguished: 1) by the number of arguments, or 2) by the types of arguments Overloading and inheritance are two ways to implement polymorphism.
Example: Overloading  class OverloadDemo { void test() { System.out.println(&quot;No parameters&quot;); } void test(int a) { System.out.println(&quot;a: &quot; + a); } void test(int a, int b) { System.out.println(&quot;a and b: &quot; + a + &quot; &quot; + b); } double test(double a) { System.out.println(&quot;double a: &quot; + a); return a*a; } }
Constructor Overloading class Box { double width, height, depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width = -1; height = -1; depth = -1; } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } }
Parameter Passing Two types of variables: 1) simple types 2) class types Two corresponding ways of how the arguments are passed to methods: 1) by value  a method receives a cope of the original value; parameters of simple types 2) by reference  a method receives the memory address of the original value, not the value itself; parameters of class types
Call by value class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.print(&quot;a and b before call: “); System.out.println(a + &quot; &quot; + b); ob.meth(a, b); System.out.print(&quot;a and b after call: &quot;); System.out.println(a + &quot; &quot; + b); } }
Call by refference As the parameter hold the same address as the argument, changes to the object inside the method do affect the object used by the argument: class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.print(&quot;ob.a and ob.b before call: “); System.out.println(ob.a + &quot; &quot; + ob.b); ob.meth(ob); System.out.print(&quot;ob.a and ob.b after call: &quot;); System.out.println(ob.a + &quot; &quot; + ob.b); } }
Recursion A recursive method is a method that calls itself: 1) all method parameters and local variables are allocated on the stack 2) arguments are prepared in the corresponding parameter positions 3) the method code is executed for the new arguments 4) upon return, all parameters and variables are removed from the stack 5) the execution continues immediately after the invocation point
Example: Recursion class Factorial { int fact(int n) { if (n==1) return 1; return fact(n-1) * n; } } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.print(&quot;Factorial of 5 is &quot;); System.out.println(f.fact(5)); }  }
String Handling String  is probably the most commonly used class in Java's class library. The obvious reason for this is that strings are a very important part of programming. The first thing to understand about strings is that every string you create is actually an object of type  String . Even string constants are actually  String  objects.  For example, in the statement System.out.println(&quot;This is a String, too&quot;); the string &quot;This is a String, too&quot; is a  String  constant
Java defines one operator for  String  objects:  + .  It is used to concatenate two strings. For example, this statement String myString = &quot;I&quot; + &quot; like &quot; + &quot;Java.&quot;; results in  myString  containing  &quot;I like Java.&quot;
The  String  class contains several methods that you can use. Here are a few. You can test two strings for equality by using  equals( ) . You can obtain the length of a string by calling the  length( )  method. You can obtain the character at a specified index within a string by calling  charAt( ) . The general forms of these three methods are shown here: // Demonstrating some String methods. class StringDemo2 { public static void main(String args[]) { String strOb1 = &quot;First String&quot;; String strOb2 = &quot;Second String&quot;; String strOb3 = strOb1; System.out.println(&quot;Length of strOb1: &quot; + strOb1.length());
System.out.println (&quot;Char at index 3 in strOb1: &quot; + strOb1.charAt(3)); if(strOb1.equals(strOb2)) System.out.println(&quot;strOb1 == strOb2&quot;); else System.out.println(&quot;strOb1 != strOb2&quot;); if(strOb1.equals(strOb3)) System.out.println(&quot;strOb1 == strOb3&quot;); else System.out.println(&quot;strOb1 != strOb3&quot;); } } This program generates the following output: Length of strOb1: 12 Char at index 3 in strOb1: s strOb1 != strOb2 strOb1 == strOb3
Ad

More Related Content

What's hot (20)

Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
Spotle.ai
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
Pushpendra Tyagi
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Java Threads
Java ThreadsJava Threads
Java Threads
M Vishnuvardhan Reddy
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
Kongu Engineering College, Perundurai, Erode
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
imypraz
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
İbrahim Kürce
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Manish Sahu
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Java String
Java StringJava String
Java String
Java2Blog
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
SameerAhmed593310
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Java packages
Java packagesJava packages
Java packages
Raja Sekhar
 

Viewers also liked (20)

Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
arnold 7490
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
arnold 7490
 
Java - Operators
Java - OperatorsJava - Operators
Java - Operators
Preethi Nambiar
 
OCA JAVA - 3 Programming with Java Operators
 OCA JAVA - 3 Programming with Java Operators OCA JAVA - 3 Programming with Java Operators
OCA JAVA - 3 Programming with Java Operators
Fernando Gil
 
Les12
Les12Les12
Les12
arnold 7490
 
Unit 1 watertech1 merged
Unit 1 watertech1 mergedUnit 1 watertech1 merged
Unit 1 watertech1 merged
anuragmbst
 
Les03
Les03Les03
Les03
arnold 7490
 
Les09
Les09Les09
Les09
arnold 7490
 
Les02
Les02Les02
Les02
arnold 7490
 
Les10
Les10Les10
Les10
arnold 7490
 
Les01
Les01Les01
Les01
arnold 7490
 
Les11
Les11Les11
Les11
arnold 7490
 
Les13
Les13Les13
Les13
arnold 7490
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15
myrajendra
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
rajveer_Pannu
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
Jasleen Kaur (Chandigarh University)
 
Unit 03 dbms
Unit 03 dbmsUnit 03 dbms
Unit 03 dbms
anuragmbst
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
arnold 7490
 
Unit 07 dbms
Unit 07 dbmsUnit 07 dbms
Unit 07 dbms
anuragmbst
 
Ad

Similar to Unit 2 Java (20)

JAVA Module 1______________________.pptx
JAVA Module 1______________________.pptxJAVA Module 1______________________.pptx
JAVA Module 1______________________.pptx
Radhika Venkatesh
 
Sambhab_Mohapatra
Sambhab_MohapatraSambhab_Mohapatra
Sambhab_Mohapatra
SAMBHAB MOHAPATRA
 
Srgoc java
Srgoc javaSrgoc java
Srgoc java
Gaurav Singh
 
Introduction to Java Basics Programming Java Basics-I.pptx
Introduction to Java Basics Programming Java Basics-I.pptxIntroduction to Java Basics Programming Java Basics-I.pptx
Introduction to Java Basics Programming Java Basics-I.pptx
SANDHYAP32
 
javaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
javaeanjjisjejrehurfhjhjfeauojksfjdi.pptjavaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
javaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
eraqhuzay69
 
Introduction-to-Programming-Languages.pptx
Introduction-to-Programming-Languages.pptxIntroduction-to-Programming-Languages.pptx
Introduction-to-Programming-Languages.pptx
ranjan317165
 
M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)
hossamghareb681
 
complete_referenceoverview.pdf
complete_referenceoverview.pdfcomplete_referenceoverview.pdf
complete_referenceoverview.pdf
zarinrafah
 
MODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxMODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptx
VeerannaKotagi1
 
thrift-20070401
thrift-20070401thrift-20070401
thrift-20070401
Hiroshi Ono
 
Unit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionUnit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introduction
AKR Education
 
Mannu_Kumar_CV
Mannu_Kumar_CVMannu_Kumar_CV
Mannu_Kumar_CV
Mannu Kumar
 
FRAUD DETECTION IN ONLINE AUCTIONING
FRAUD DETECTION IN ONLINE AUCTIONINGFRAUD DETECTION IN ONLINE AUCTIONING
FRAUD DETECTION IN ONLINE AUCTIONING
Satish Chandra
 
Dot net
Dot netDot net
Dot net
public
 
Gervais Peter Resume Oct :2015
Gervais Peter Resume Oct :2015Gervais Peter Resume Oct :2015
Gervais Peter Resume Oct :2015
Peter Gervais
 
Birendra_resume
Birendra_resumeBirendra_resume
Birendra_resume
birendra kumar
 
Gaurav agarwal
Gaurav agarwalGaurav agarwal
Gaurav agarwal
Gaurav Agarwal
 
Manoj_cv
Manoj_cvManoj_cv
Manoj_cv
Manoj Mariappan
 
Object Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptxObject Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptx
ASHWINIGOWDA46
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
Maarten Balliauw
 
JAVA Module 1______________________.pptx
JAVA Module 1______________________.pptxJAVA Module 1______________________.pptx
JAVA Module 1______________________.pptx
Radhika Venkatesh
 
Introduction to Java Basics Programming Java Basics-I.pptx
Introduction to Java Basics Programming Java Basics-I.pptxIntroduction to Java Basics Programming Java Basics-I.pptx
Introduction to Java Basics Programming Java Basics-I.pptx
SANDHYAP32
 
javaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
javaeanjjisjejrehurfhjhjfeauojksfjdi.pptjavaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
javaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
eraqhuzay69
 
Introduction-to-Programming-Languages.pptx
Introduction-to-Programming-Languages.pptxIntroduction-to-Programming-Languages.pptx
Introduction-to-Programming-Languages.pptx
ranjan317165
 
M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)
hossamghareb681
 
complete_referenceoverview.pdf
complete_referenceoverview.pdfcomplete_referenceoverview.pdf
complete_referenceoverview.pdf
zarinrafah
 
MODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxMODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptx
VeerannaKotagi1
 
Unit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionUnit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introduction
AKR Education
 
FRAUD DETECTION IN ONLINE AUCTIONING
FRAUD DETECTION IN ONLINE AUCTIONINGFRAUD DETECTION IN ONLINE AUCTIONING
FRAUD DETECTION IN ONLINE AUCTIONING
Satish Chandra
 
Gervais Peter Resume Oct :2015
Gervais Peter Resume Oct :2015Gervais Peter Resume Oct :2015
Gervais Peter Resume Oct :2015
Peter Gervais
 
Object Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptxObject Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptx
ASHWINIGOWDA46
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
Maarten Balliauw
 
Ad

More from arnold 7490 (15)

Les14
Les14Les14
Les14
arnold 7490
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
arnold 7490
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
arnold 7490
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
arnold 7490
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
arnold 7490
 
Unit3 C
Unit3 C Unit3 C
Unit3 C
arnold 7490
 
Unit2 C
Unit2 C Unit2 C
Unit2 C
arnold 7490
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
arnold 7490
 
Unit7 C
Unit7 CUnit7 C
Unit7 C
arnold 7490
 
Unit2 C
Unit2 CUnit2 C
Unit2 C
arnold 7490
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
arnold 7490
 
Unit8 C
Unit8 CUnit8 C
Unit8 C
arnold 7490
 

Recently uploaded (20)

Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 

Unit 2 Java

  • 2. INDEX UNIT 2 PPT SLIDES S.NO. TOPIC LECTURE NO. PPTSLIDES History of Java, L1 L1.1TO L1.20 Java buzzwords, data types . variables, scope and life time of variables, L2 L2.1 TO L2.20 arrays, operators, expressions control statements, L3 L3.1 TO L3.9 type conversion and costing simple java program, L 4 L4.1 TO L4.8 classes and objects – concepts of classes objects, constructors, methods L5 L5.1 TO 5.6 Access control, this keyword, L6 L6.1 TO 6.8 garbage collection 7 overloading methods and constructors, L7 L7.1 TO 7.6 parameter passing 8 R ecursion, string handling. L8 L 8.1 TO 8.6
  • 3. Java History Computer language innovation and development occurs for two fundamental reasons: 1) to adapt to changing environments and uses 2) to implement improvements in the art of programming The development of Java was driven by both in equal measures. Many Java features are inherited from the earlier languages: B  C  C++  Java
  • 4. Before Java: C Designed by Dennis Ritchie in 1970s. Before C: BASIC, COBOL, FORTRAN, PASCAL C- structured, efficient, high-level language that could replace assembly code when creating systems programs. Designed, implemented and tested by programmers.
  • 5. Before Java: C++ Designed by Bjarne Stroustrup in 1979. Response to the increased complexity of programs and respective improvements in the programming paradigms and methods: 1) assembler languages 2) high-level languages 3) structured programming 4) object-oriented programming (OOP) OOP – methodology that helps organize complex programs through the use of inheritance, encapsulation and polymorphism. C++ extends C by adding object-oriented features.
  • 6. Java: History In 1990, Sun Microsystems started a project called Green. Objective: to develop software for consumer electronics. Project was assigned to James Gosling, a veteran of classic network software design. Others included Patrick Naughton, ChrisWarth, Ed Frank, and Mike Sheridan. The team started writing programs in C++ for embedding into – toasters – washing machines – VCR’s Aim was to make these appliances more “intelligent”.
  • 7. Java: History (contd.) C++ is powerful, but also dangerous. The power and popularity of C derived from the extensive use of pointers. However, any incorrect use of pointers can cause memory leaks, leading the program to crash. In a complex program, such memory leaks are often hard to detect. Robustness is essential. Users have come to expect that Windows may crash or that a program running under Windows may crash. (“This program has performed an illegal operation and will be shut down”) However, users do not expect toasters to crash, or washing machines to crash. A design for consumer electronics has to be robust . Replacing pointers by references, and automating memory management was the proposed solution.
  • 8. Java: History (contd.) Hence, the team built a new programming language called Oak, which avoided potentially dangerous constructs in C++, such as pointers, pointer arithmetic, operator overloading etc. Introduced automatic memory management, freeing the programmer to concentrate on other things. Architecture neutrality (Platform independence) Many different CPU’s are used as controllers. Hardware chips are evolving rapidly. As better chips become available, older chips become obsolete and their production is stopped. Manufacturers of toasters and washing machines would like to use the chips available off the shelf, and would not like to reinvest in compiler development every two-three years. So, the software and programming language had to be architecture neutral .
  • 9. Java: History (contd) It was soon realized that these design goals of consumer electronics perfectly suited an ideal programming language for the Internet and WWW, which should be: object-oriented (& support GUI) – robust – architecture neutral Internet programming presented a BIG business opportunity. Much bigger than programming for consumer electronics. Java was “re-targeted” for the Internet The team was expanded to include Bill Joy (developer of Unix), Arthur van Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc. In 1994, an early web browser called WebRunner was written in Oak. WebRunner was later renamed HotJava. In 1995, Oak was renamed Java. A common story is that the name Java relates to the place from where the development team got its coffee. The name Java survived the trade mark search.
  • 10. Java History Designed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan at Sun Microsystems in 1991. The original motivation is not Internet: platform-independent software embedded in consumer electronics devices. With Internet, the urgent need appeared to break the fortified positions of Intel, Macintosh and Unix programmer communities. Java as an “Internet version of C++”? No. Java was not designed to replace C++, but to solve a different set of problems.
  • 11. The Java Buzzwords The key considerations were summed up by the Java team in the following list of buzzwords: Simple Secure Portable Object-oriented Robust Multithreaded Architecture-neutral Interpreted High performance Distributed Dynamic
  • 12. simple – Java is designed to be easy for the professional programmer to learn and use. object-oriented: a clean, usable, pragmatic approach to objects, not restricted by the need for compatibility with other languages. Robust: restricts the programmer to find the mistakes early, performs compile-time (strong typing) and run-time (exception-handling) checks, manages memory automatically. Multithreaded: supports multi-threaded programming for writing program that perform concurrent computations
  • 13. Architecture-neutral: Java Virtual Machine provides a platform independent environment for the execution of Java byte code Interpreted and high-performance: Java programs are compiled into an intermediate representation – byte code: a) can be later interpreted by any JVM b) can be also translated into the native machine code for efficiency.
  • 14. Distributed: Java handles TCP/IP protocols, accessing a resource through its URL much like accessing a local file. Dynamic: substantial amounts of run-time type information to verify and resolve access to objects at run-time. Secure: programs are confined to the Java execution environment and cannot access other parts of the computer.
  • 15. Portability: Many types of computers and operating systems are in use throughout the world—and many are connected to the Internet. For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed. The same mechanism that helps ensure security also helps create portability. Indeed, Java's solution to these two problems is both elegant and efficient.
  • 16. Data Types Java defines eight simple types: 1)byte – 8-bit integer type 2)short – 16-bit integer type 3)int – 32-bit integer type 4)long – 64-bit integer type 5)float – 32-bit floating-point type 6)double – 64-bit floating-point type 7)char – symbols in a character set 8)boolean – logical values true and false
  • 17. byte: 8-bit integer type. Range: -128 to 127. Example: byte b = -15; Usage: particularly when working with data streams. short: 16-bit integer type. Range: -32768 to 32767. Example: short c = 1000; Usage: probably the least used simple type.
  • 18. int: 32-bit integer type. Range: -2147483648 to 2147483647. Example: int b = -50000; Usage: 1) Most common integer type. 2) Typically used to control loops and to index arrays. 3) Expressions involving the byte, short and int values are promoted to int before calculation.
  • 19. long: 64-bit integer type. Range: -9223372036854775808 to 9223372036854775807. Example: long l = 10000000000000000; Usage: 1) useful when int type is not large enough to hold the desired value float: 32-bit floating-point number. Range: 1.4e-045 to 3.4e+038. Example: float f = 1.5; Usage: 1) fractional part is needed 2) large degree of precision is not required
  • 20. double: 64-bit floating-point number. Range: 4.9e-324 to 1.8e+308. Example: double pi = 3.1416; Usage: 1) accuracy over many iterative calculations 2) manipulation of large-valued numbers
  • 21. char: 16-bit data type used to store characters. Range: 0 to 65536. Example: char c = ‘a’; Usage: 1) Represents both ASCII and Unicode character sets; Unicode defines a character set with characters found in (almost) all human languages. 2) Not the same as in C/C++ where char is 8-bit and represents ASCII only.
  • 22. boolean: Two-valued type of logical values. Range: values true and false. Example: boolean b = (1<2); Usage: 1) returned by relational operators, such as 1<2 2) required by branching expressions such as if or for
  • 23. Variables declaration – how to assign a type to a variable initialization – how to give an initial value to a variable scope – how the variable is visible to other parts of the program lifetime – how the variable is created, used and destroyed type conversion – how Java handles automatic type conversion type casting – how the type of a variable can be narrowed down type promotion – how the type of a variable can be expanded
  • 24. Variables Java uses variables to store data. To allocate memory space for a variable JVM requires: 1) to specify the data type of the variable 2) to associate an identifier with the variable 3) optionally, the variable may be assigned an initial value All done as part of variable declaration.
  • 25. Basic Variable Declaration datatype identifier [=value]; datatype must be A simple datatype User defined datatype (class type) Identifier is a recognizable name confirm to identifier rules Value is an optional initial value.
  • 26. Variable Declaration We can declare several variables at the same time: type identifier [=value][, identifier [=value] …]; Examples: int a, b, c; int d = 3, e, f = 5; byte g = 22; double pi = 3.14159; char ch = 'x';
  • 27. Variable Scope Scope determines the visibility of program elements with respect to other program elements. In Java, scope is defined separately for classes and methods: 1) variables defined by a class have a global scope 2) variables defined by a method have a local scope A scope is defined by a block: { … } A variable declared inside the scope is not visible outside: { int n; } n = 1;// this is illegal
  • 28. Variable Lifetime Variables are created when their scope is entered by control flow and destroyed when their scope is left: A variable declared in a method will not hold its value between different invocations of this method. A variable declared in a block looses its value when the block is left. Initialized in a block, a variable will be re-initialized with every re-entry. Variables lifetime is confined to its scope!
  • 29. Arrays An array is a group of liked-typed variables referred to by a common name, with individual variables accessed by their index. Arrays are: 1) declared 2) created 3) initialized 4) used Also, arrays can have one or several dimensions.
  • 30. Array Declaration Array declaration involves: 1) declaring an array identifier 2) declaring the number of dimensions 3) declaring the data type of the array elements Two styles of array declaration: type array-variable[]; or type [] array-variable;
  • 31. Array Creation After declaration, no array actually exists. In order to create an array, we use the new operator: type array-variable[]; array-variable = new type[size]; This creates a new array to hold size elements of type type, which reference will be kept in the variable array-variable.
  • 32. Array Indexing Later we can refer to the elements of this array through their indexes: array-variable[index] The array index always starts with zero! The Java run-time system makes sure that all array indexes are in the correct range, otherwise raises a run-time error.
  • 33. Array Initialization Arrays can be initialized when they are declared: int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31}; Note: 1) there is no need to use the new operator 2) the array is created large enough to hold all specified elements
  • 34. Multidimensional Arrays Multidimensional arrays are arrays of arrays: 1) declaration: int array[][]; 2) creation: int array = new int[2][3]; 3) initialization int array[][] = { {1, 2, 3}, {4, 5, 6} };
  • 35. Operators Types Java operators are used to build value expressions. Java provides a rich set of operators: 1) assignment 2) arithmetic 3) relational 4) logical 5) bitwise
  • 36. Arithmetic assignments v = v % expr ; v %= expr; %= v = v / expr ; v /= expr; /= v = v * expr ; v *= expr; *= v = v - expr ; v -=expr; -= v = v + expr ; v += expr; +=
  • 37. Basic Arithmetic Operators REMAINDER op1 % op2 % DIVISION op1 / op2 / MULTIPLY op1 * op2 * SUBSTRACT op1 - op2 - ADD op1 + op2 +
  • 38. Relational operator Apply to numerical type Less than or equal <= Apply to numerical type Greater than or equal >= Apply to numerical type Less than < Apply to numerical type Greater than > Apply to any type Not equals to != Apply to any type Equals to ==
  • 39. Logical operators Logical XOR op1 ^ op2 ^ Logical NOT ! op ! Short-circuit OR op1 || op2 || Short-circuit AND op1 && op2 && Logical OR op1 | op2 | Logical AND op1 & op2 &
  • 40. Bit wise operators Shifts all bits in op1 left by the value of op2 op1 << op2 << Shifts all bits in op1 right by the value of op2 op1 >> op2 >> Produces 1 bit if exactly one operand is 1 op1 ^ op2 ^ Produces 1 bit if either operand is 1 op1 |op2 | Produces 1 bit if both operands are 1 op1 & op2 & Inverts all bits ~op ~
  • 41. An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. Examples of expressions are in bold below: int number = 0 ; anArray[0] = 100 ; System.out.println ( &quot;Element 1 at index 0: &quot; + anArray[0] ); int result = 1 + 2 ; // result is now 3 if( value1 == value2 ) System.out.println( &quot;value1 == value2&quot; ); Expressions
  • 42. Expressions The data type of the value returned by an expression depends on the elements used in the expression. The expression number = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, number is an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String. The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression: 1 * 2 * 3
  • 43. Control Statements Java control statements cause the flow of execution to advance and branch based on the changes to the state of the program. Control statements are divided into three groups: 1) selection statements allow the program to choose different parts of the execution based on the outcome of an expression 2) iteration statements enable program execution to repeat one or more statements 3) jump statements enable your program to execute in a non-linear fashion
  • 44. Selection Statements Java selection statements allow to control the flow of program’s execution based upon conditions known only during run-time. Java provides four selection statements: 1) if 2) if-else 3) if-else-if 4) switch
  • 45. Iteration Statements Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true. Java provides three iteration statements: 1) while 2) do-while 3) for
  • 46. Jump Statements Java jump statements enable transfer of control to other parts of program. Java provides three jump statements: 1) break 2) continue 3) return In addition, Java supports exception handling that can also alter the control flow of a program.
  • 47. Type Conversion Size Direction of Data Type Widening Type Conversion (Casting down) Smaller Data Type  Larger Data Type Narrowing Type Conversion (Casting up) Larger Data Type  Smaller Data Type Conversion done in two ways Implicit type conversion Carried out by compiler automatically Explicit type conversion Carried out by programmer using casting
  • 48. Type Conversion Widening Type Converstion Implicit conversion by compiler automatically byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double float -> double
  • 49. Type Conversion Narrowing Type Conversion Programmer should describe the conversion explicitly byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long double -> byte, short, char, int, long, float
  • 50. Type Conversion byte and short are always promoted to int if one operand is long, the whole expression is promoted to long if one operand is float, the entire expression is promoted to float if any operand is double, the result is double
  • 51. Type Casting General form: (targetType) value Examples: 1) integer value will be reduced module bytes range: int i; byte b = (byte) i; 2) floating-point value will be truncated to integer value: float f; int i = (int) f;
  • 52. Simple Java Program A class to display a simple message: class MyProgram { public static void main(String[] args) { System.out.println(“First Java program.&quot;); } }
  • 53. What is an Object? Real world objects are things that have: 1) state 2) behavior Example: your dog: state – name, color, breed, sits?, barks?, wages tail?, runs? behavior – sitting, barking, waging tail, running A software object is a bundle of variables (state) and methods (operations).
  • 54. What is a Class? A class is a blueprint that defines the variables and methods common to all objects of a certain kind. Example: ‘your dog’ is a object of the class Dog. An object holds values for the variables defines in the class. An object is called an instance of the Class
  • 55. Object Creation A variable is declared to refer to the objects of type/class String: String s; The value of s is null; it does not yet refer to any object. A new String object is created in memory with initial “abc” value: String s = new String(“abc”); Now s contains the address of this new object.
  • 56. Object Destruction A program accumulates memory through its execution. Two mechanism to free memory that is no longer need by the program: 1) manual – done in C/C++ 2) automatic – done in Java In Java, when an object is no longer accessible through any variable, it is eventually removed from the memory by the garbage collector. Garbage collector is parts of the Java Run-Time Environment.
  • 57. Class A basis for the Java language. Each concept we wish to describe in Java must be included inside a class. A class defines a new data type, whose values are objects: A class is a template for objects An object is an instance of a class
  • 58. Class Definition A class contains a name, several variable declarations (instance variables) and several method declarations. All are called members of the class. General form of a class: class classname { type instance-variable-1; … type instance-variable-n; type method-name-1(parameter-list) { … } type method-name-2(parameter-list) { … } … type method-name-m(parameter-list) { … } }
  • 59. Example: Class Usage class Box { double width; double height; double depth; } class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println (&quot;Volume is &quot; + vol); } }
  • 60. Constructor A constructor initializes the instance variables of an object. It is called immediately after the object is created but before the new operator completes. 1) it is syntactically similar to a method: 2) it has the same name as the name of its class 3) it is written without return type; the default return type of a class constructor is the same class When the class has no constructor, the default constructor automatically initializes all its instance variables with zero.
  • 61. Example: Constructor class Box { double width; double height; double depth; Box() { System.out.println(&quot;Constructing Box&quot;); width = 10; height = 10; depth = 10; } double volume() { return width * height * depth; } }
  • 62. Parameterized Constructor class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { return width * height * depth; } }
  • 63. Methods General form of a method definition: type name(parameter-list) { … return value; … } Components: 1) type - type of values returned by the method. If a method does not return any value, its return type must be void. 2) name is the name of the method 3) parameter-list is a sequence of type-identifier lists separated by commas 4) return value indicates what value is returned by the method.
  • 64. Example: Method Classes declare methods to hide their internal data structures, as well as for their own internal use: Within a class, we can refer directly to its member variables: class Box { double width, height, depth; void volume() { System.out.print(&quot;Volume is &quot;); System.out.println(width * height * depth); } }
  • 65. Parameterized Method Parameters increase generality and applicability of a method: 1) method without parameters int square() { return 10*10; } 2) method with parameters int square(int i) { return i*i; } Parameter: a variable receiving value at the time the method is invoked. Argument: a value passed to the method when it is invoked.
  • 66. Access Control: Data Hiding and Encapsulation Java provides control over the visibility of variables and methods. Encapsulation, safely sealing data within the capsule of the class Prevents programmers from relying on details of class implementation, so you can update without worry Helps in protecting against accidental or wrong usage. Keeps code elegant and clean (easier to maintain)
  • 67. Access Modifiers: Public, Private, Protected Public: keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. Default(No visibility modifier is specified): it behaves like public in its package and private in other packages. Default Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible.
  • 68. Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.
  • 69. Visibility public class Circle { private double x,y,r; // Constructor public Circle (double x, double y, double r) { this.x = x; this.y = y; this.r = r; } //Methods to return circumference and area public double circumference() { return 2*3.14*r;} public double area() { return 3.14 * r * r; } }
  • 70. Keyword this Can be used by any object to refer to itself in any class method Typically used to Avoid variable name collisions Pass the receiver as an argument Chain constructors
  • 71. Keyword this Keyword this allows a method to refer to the object that invoked it. It can be used inside any method to refer to the current object: Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }
  • 72. Garbage Collection Garbage collection is a mechanism to remove objects from memory when they are no longer needed. Garbage collection is carried out by the garbage collector: 1) The garbage collector keeps track of how many references an object has. 2) It removes an object from memory when it has no longer any references. 3) Thereafter, the memory occupied by the object can be allocated again. 4) The garbage collector invokes the finalize method.
  • 73. finalize() Method A constructor helps to initialize an object just after it has been created. In contrast, the finalize method is invoked just before the object is destroyed: 1) implemented inside a class as: protected void finalize() { … } 2) implemented when the usual way of removing objects from memory is insufficient, and some special actions has to be carried out
  • 74. Method Overloading It is legal for a class to have two or more methods with the same name. However, Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments. Therefore the same-named methods must be distinguished: 1) by the number of arguments, or 2) by the types of arguments Overloading and inheritance are two ways to implement polymorphism.
  • 75. Example: Overloading class OverloadDemo { void test() { System.out.println(&quot;No parameters&quot;); } void test(int a) { System.out.println(&quot;a: &quot; + a); } void test(int a, int b) { System.out.println(&quot;a and b: &quot; + a + &quot; &quot; + b); } double test(double a) { System.out.println(&quot;double a: &quot; + a); return a*a; } }
  • 76. Constructor Overloading class Box { double width, height, depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width = -1; height = -1; depth = -1; } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } }
  • 77. Parameter Passing Two types of variables: 1) simple types 2) class types Two corresponding ways of how the arguments are passed to methods: 1) by value a method receives a cope of the original value; parameters of simple types 2) by reference a method receives the memory address of the original value, not the value itself; parameters of class types
  • 78. Call by value class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.print(&quot;a and b before call: “); System.out.println(a + &quot; &quot; + b); ob.meth(a, b); System.out.print(&quot;a and b after call: &quot;); System.out.println(a + &quot; &quot; + b); } }
  • 79. Call by refference As the parameter hold the same address as the argument, changes to the object inside the method do affect the object used by the argument: class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.print(&quot;ob.a and ob.b before call: “); System.out.println(ob.a + &quot; &quot; + ob.b); ob.meth(ob); System.out.print(&quot;ob.a and ob.b after call: &quot;); System.out.println(ob.a + &quot; &quot; + ob.b); } }
  • 80. Recursion A recursive method is a method that calls itself: 1) all method parameters and local variables are allocated on the stack 2) arguments are prepared in the corresponding parameter positions 3) the method code is executed for the new arguments 4) upon return, all parameters and variables are removed from the stack 5) the execution continues immediately after the invocation point
  • 81. Example: Recursion class Factorial { int fact(int n) { if (n==1) return 1; return fact(n-1) * n; } } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.print(&quot;Factorial of 5 is &quot;); System.out.println(f.fact(5)); } }
  • 82. String Handling String is probably the most commonly used class in Java's class library. The obvious reason for this is that strings are a very important part of programming. The first thing to understand about strings is that every string you create is actually an object of type String . Even string constants are actually String objects. For example, in the statement System.out.println(&quot;This is a String, too&quot;); the string &quot;This is a String, too&quot; is a String constant
  • 83. Java defines one operator for String objects: + . It is used to concatenate two strings. For example, this statement String myString = &quot;I&quot; + &quot; like &quot; + &quot;Java.&quot;; results in myString containing &quot;I like Java.&quot;
  • 84. The String class contains several methods that you can use. Here are a few. You can test two strings for equality by using equals( ) . You can obtain the length of a string by calling the length( ) method. You can obtain the character at a specified index within a string by calling charAt( ) . The general forms of these three methods are shown here: // Demonstrating some String methods. class StringDemo2 { public static void main(String args[]) { String strOb1 = &quot;First String&quot;; String strOb2 = &quot;Second String&quot;; String strOb3 = strOb1; System.out.println(&quot;Length of strOb1: &quot; + strOb1.length());
  • 85. System.out.println (&quot;Char at index 3 in strOb1: &quot; + strOb1.charAt(3)); if(strOb1.equals(strOb2)) System.out.println(&quot;strOb1 == strOb2&quot;); else System.out.println(&quot;strOb1 != strOb2&quot;); if(strOb1.equals(strOb3)) System.out.println(&quot;strOb1 == strOb3&quot;); else System.out.println(&quot;strOb1 != strOb3&quot;); } } This program generates the following output: Length of strOb1: 12 Char at index 3 in strOb1: s strOb1 != strOb2 strOb1 == strOb3