Docsity

oop enotes for summarize, Summaries of Object Oriented Programming

Toggle sidebar
bg1
1 - Basics of Java
1
Prof. Swati R. Sharma
| 3140705 – Object Oriented Programming - I
History of JAVA.
Java was initially developed in 1991 named as “oak” but was renamed “Java” in 1995.
Originally designed for small, embedded systems in electronic appliances like set-top boxes.
The primary motivation was the need for a platform-independent language that could be used
to create software to be embedded in various consumer electronic devices.
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java
platform (Java 1.0 [J2SE]).
It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular
platforms.
Java 2, new versions had multiple configurations built for different types of platforms. J2EE
included technologies and APIs for enterprise applications typically run in server
environments, while J2ME featured APIs optimized for mobile applications.
The desktop version was renamed J2SE. In 2006, for marketing purposes, Sun renamed new
J2 versions as Java EE, Java ME, and Java SE, respectively.
On 13 November 2006, Sun released much of Java as free and open-source software (FOSS),
under the terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source,
aside from a small portion of code to which Sun did not hold the copyright.
What is Java?
Java is a programming language that:
Is exclusively object oriented
Has full GUI support
Has full network support
Is platform independent
Executes stand-alone or “on-demand” in web browser as applets
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download oop enotes for summarize and more Summaries Object Oriented Programming in PDF only on Docsity!

History of JAVA.

 Java was initially developed in 1991 named as “oak” but was renamed “Java” in 1995.  Originally designed for small, embedded systems in electronic appliances like set-top boxes.  The primary motivation was the need for a platform-independent language that could be used to create software to be embedded in various consumer electronic devices.  Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).  It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.  Java 2, new versions had multiple configurations built for different types of platforms. J2EE included technologies and APIs for enterprise applications typically run in server environments, while J2ME featured APIs optimized for mobile applications.  The desktop version was renamed J2SE. In 2006, for marketing purposes, Sun renamed new J2 versions as Java EE, Java ME, and Java SE, respectively.  On 13 November 2006, Sun released much of Java as free and open-source software (FOSS), under the terms of the GNU General Public License (GPL).  On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.

What is Java?

 Java is a programming language that:  Is exclusively object oriented  Has full GUI support  Has full network support  Is platform independent  Executes stand-alone or “on-demand” in web browser as applets

JDK, JRE, Byte code & JVM.

Java Development Kit (JDK) o JDK contains tools needed ,  To develop the Java programs and  JRE to run the programs. o The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc… o Java application launcher (java.exe),  Opens a JRE, loads the class, and invokes its main method.  Java Runtime Environment (JRE) o The Java Runtime Environment (JRE) is required to run java applications. o It combines the Java Virtual Machine (JVM), platform core classes and supporting libraries. o JRE is part of the Java Development Kit (JDK), but can be downloaded separately. o It does not contain any development tools such as compiler, debugger, etc.  Byte code o Byte code is intermediate representation of java source code. o It produce by java compiler by compiling java source code. o Extension for java class file or byte code is ‘.class’. o It is platform independent.

Compiler

(Javac.exe)

Java

Application

Launcher

(java.exe),

AppletViewer,

etc..)

Java

Packages

(math,

Runtime

Libraries

JVM

Development tools JRE

JDK

Simple o It’s simple because it contains many features of other languages like C and C++ o It also removed complexities like pointers, Storage classes, goto statement and multiple Inheritance.  Secure o Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

  1. No explicit pointer
  2. Java Programs run inside virtual machine sandbox
  3. Bytecode Verifier  Portable o Java is portable because it facilitates you to carry the java bytecode to any platform.  Object oriented o Java is Object-oriented programming language. Everything in Java is an object.  Robust o Robust simply means strong. Java is robust because:
  4. It uses strong memory management.
  5. There are lack of pointers that avoids security problem.
  6. There is automatic garbage collection in java.
  7. There is exception handling and type checking mechanism in java. All these points makes java robust  Multithreaded o A thread is like a separate program, executing concurrently. o We can write Java programs that deal with many tasks at once by defining multiple threads. o The main advantage of multi-threading is that it doesn't occupy memory for each thread. o It shares a common memory area. Threads are important for multi-media, Web applications etc…  Architecture-neutral o Java is architecture neutral because there is no implementation dependent features e.g. size of primitive types is fixed. o Example : in c int occupy 2 byte for 32 bit OS and 4 bytes for 64 bit OS whereas in JAVA it occupy 4 byte for int both in 32 bit and 64 bit OS.  Interpreted o Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. o This code can be executed on any system that implements the Java Virtual Machine.  High-Performance o Most previous attempts at cross-platform solutions have done so at the expense of performance. o As explained earlier, the Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler.  Dynamic o Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. o This makes it possible to dynamically link code in a safe and expedient manner.

Distributed o Java is distributed because it facilitates us to create distributed applications in java. o RMI and EJB are used for creating distributed applications. o We may access files by calling the methods from any machine on the internet.  Platform Independent o Java is a platform independent programming language, because when you install JDK in the system then JVM is also installed automatically on the system. o For every operating system separate JVM is available which is capable to read the .class file or byte code. o When we compile Java code then .class file is generated by java compiler (javac) these codes are readable by the JVM and every operating system have its own JVM so JVM is platform dependent but due to JVM java is platform independent.

Explain Operators in JAVA

Sr. Operator Examples

1 Arithmetic Operators +, - , *, /, % 2 Relational Operators <, <=, >, >=, ==, != 3 Logical Operators &&, ||,! 4 Assignment Operators =, +=, - =, *=, /= 5 Increment and Decrement Operators ++, -- 6 Conditional Operator ?: 7 Bitwise Operators &, |, ^, <<, >>

Arithmetic Operator

 An arithmetic operator performs basic mathematical calculations such as addition, subtraction, multiplication, division etc. on numerical values (constants and variables).  Increment / Decrement Operators o Increment and decrement operators are unary operators that add or subtract one, to or from their operand. o the increment operator ++ increases the value of a variable by 1, e.g. a++ means a=a+ o the decrement operator -- decreases the value of a variable by 1. e.g. a–– means a=a– 1 o If ++ operator is used as a prefix (++a) then the value of a is incremented by 1 first then it returns the value. o If ++ operator is used as a postfix (a++) then the value of a is returned first then it increments value of a by 1.

Bitwise Operators

Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand.

(A | B) will give 61 which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

(~A ) will give - 61 which is 1100 0011 in 2's complement form due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 1111

>>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

A >>>2 will give 15 which is 0000 1111

Bitwise Operators in JAVA, consider A as 60 & B as 13

Logical Operators

 Logical operators are decision making operators.  They are used to combine two expressions and make decisions.  An expression containing logical operator returns either 0 or 1 depending upon whether expression results false or true.

Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

(A && B) is false. || Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.

(A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is true. Logical Operators in JAVA, consider A as true & B as false

Assignment Operators

 Assignment operators are used to assign a new value to the variable.  The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value or a result of an expression.  Meaning of = in Maths and Programming is different. o Value of LHS & RHS is always same in Math. o In programming, value of RHS is assigned to the LHS Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assign value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

  • = Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C - = A is equivalent to C = C - A

*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A <<= Left shift AND assignment operator C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator C &= 2 is same as C = C & 2 ^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2 |= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2 Assignment Operators in JAVA

Explain short circuit operators.

 Java provides two interesting Boolean operators not found in many other computer languages. These are secondary versions of the Boolean AND and OR operators, and are known as shortcircuit logical operators.  The OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand when the outcome of the expression can be determined by the left operand alone.  This is very useful when the right-hand operand depends on the value of the left one in order to function properly. For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it: if (denom != 0 && num / denom > 10)  Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception when denom is zero. If this line of code were written using the single & version of AND, both sides would be evaluated, causing a run-time exception when denom is zero. It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single- character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement: if(c==1 & e++ < 100) d = 100)  Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.

Explain primitive Data types of JAVA.

Java defines 8 primitive types: Data Type Size Range Example byte 1 Byte -128 to 127 byte a = 10; short 2 Bytes -32,768 to 32,767 short a = 200; int 4 Bytes -2,147,483,648 to 2,147,483,647 int a = 50000; long 8 Bytes -9,223,372,036,854,775,80 to 9,223,372,036,854,775,807 long a = 20; float 4 Bytes 1.4e-045 to 3.4e+038 float a = 10.2f; double 8 Bytes 4.9e-324 to 1.8e+308 double a = 10.2; char 2 Bytes 0 to 65536 (Stores ASCII of character) char a = ‘a’; boolean Not defined

true or false boolean a = true;

byte o Smallest integer type o It is a signed 8-bit type ( 1 Byte ) o Range is -128 to 127 o Especially useful when working with stream of data from a network or file o Example: byte b = 10;  short o short is signed 16-bit ( 2 Byte ) type o Range : -32768 to 32767 o It is probably least used Java type o Example: short vId = 1234;  int o The most commonly used type o It is signed 32-bit ( 4 Byte ) type o Range: -2,147,483,648 to 2,147,483, o Example: int a = 1234;  long o long is signed 64-bit ( 8 Byte ) type o It is useful when int type is not large enough to hold the desired value o Example: long soconds = 1234124231;  char o It is 16-bit ( 2 Byte ) type o Range: 0 to 65, o Example: char first = ‘A’; char second = 65;  float o It is 32-bit ( 4-Byte ) type o It specifies a single-precision value o Example: float price = 1234.45213 fdouble o It uses 64-bit ( 8-Byte ) o All math functions such as sin(),cos(),sqrt() etc… returns double value o Example: double pi = 3.14141414141414;  boolean o The boolean data type has only two possible values: true and false. o This data type represents one bit of information, but its "size" isn't something that's precisely defined.

Program Structure, Compilation and Run Process

Simple Java Program Structure

public class Example { public static void main(String args[]) { System.out.println(“First Example”); } }

class Example Here name of the class is Example.  public static void main(String args[])  public: The public keyword is an access specifier, which means that the content of the following block accessible from all other classes.  static: The keyword static allows main() to be called without having to instantiate a particular instance of a class.  void: The keyword void tells the compiler that main() does not return a value. The methods can return value.  main(): main is a method called when a java application begins,  String args [] Declares a parameter named args, which is an array of instance of the class string.

Args[] receives any command-line argument present when the program is executed.

System.out.println()  System is predefined class that provides access to the system.  Out is the output stream that is connected to the console.  Output is accomplished by the built-in println() method. Println() displays the string which is passed to it.

Compilation of Java Program

Figure 1.4. Java Program Compilation Process

Example

.java

Example

.class

javac java

Source Code bytecode compiler bytecode file Interpreter (VM)

Command 1: Javac Example.java This command will compile the source file and if the compilation is successful, it will generate a file named example.class containing bytecode. Java compilers translate java program to bytecode form.  Command 2 : Java Example The command called ‘java’ takes the bytecode and runs the bytecode on JVM  Output First Example

Type Casting

 Assigning a value of one type to a variable of another type is known as Type Casting.  In Java, type casting is classified into two types,  Widening/Automatic Type Casting (Implicit)

Widening/Automatic Type Casting (Implicit)

Narrowing Type Casting (Explicitly done)

Automatic Type Casting

 When one type of data is assigned to other type of variable , an automatic type conversion will take place if the following two conditions are satisfied:  The two types are compatible  The destination type is larger than the source type  Such type of casting is called “widening conversion”.  Example: int can always hold values of byte and short public static void main(String[] args) { byte b = 5; // √ this is correct int a = b; }

2 – Selections, Mathematical functions & loops

Decision Making Statements

 Compiler executes program statements sequentially.  Decision making statements are used to control the flow of program execution.  It allows us to control whether a set of program statement should be executed or not.  It evaluates condition or logical expression first and based on its result (true or false), the control is transferred to the particular statement.  If result is true then it takes one path else it takes another path.

Commonly used decision making statements are:

  1. One way Decision: if (Also known as simple if)
  2. Two way Decision: if…else
  3. Multi way Decision: if…else if…else if…else
  4. Decision within Decision: nested if
  5. Two way Decision: ?: (Conditional Operator)
  6. n-way Decision: switch…case

If Statement

 if statement is the most simple decision-making statement also known as simple if.  if statement consists of a Boolean expression followed by one or more statements.  If the expression is true, then 'statement-inside' will be executed, otherwise 'statement-inside' is skipped and only 'statement-outside' will be executed.  It is used to decide whether a block of statements will be executed or not i.e. if a certain condition is true then a block of statement is executed otherwise not.

2 – Selections, Mathematical functions & loops

WAP to print if a number is positive

  1. import java.util.*;
  2. class MyProgram{
  3. public static void main (String[] args){
  4. int x;
  5. Scanner sc = new Scanner(System.in);
  6. x = sc.nextInt();
  7. if(x > 0){
  8. System.out.println("number is a positive");
  9. }
  10. }

WAP to print if a number is odd or even

  1. import java.util.*;
  2. class MyProgram{
  3. public static void main (String[] args){
  4. int x;
  5. Scanner sc = new Scanner(System.in);
  6. x = sc.nextInt();
  7. if( x % 2 == 1 ){
  8. System.out.println("number is a odd");
  9. }
  10. if( x % 2 == 0 ){
  11. System.out.println("number is a even");
  12. }
  13. }

If…else: Two way Decision

 For a simple if, if a condition is true, the compiler executes a block of statements, if condition is false then it doesn’t do anything.  What if we want to do something when the condition is false? if…else is used for the same.  If the 'expression' is true then the 'statement-block-1' will get executed else 'statement- block-2' will be executed if(condition) { // statement-block- 1 // to execute if condition is true } else { // statement-block- 2 // to execute if condition is false }

2 – Selections, Mathematical functions & loops

if-else-if ladder

 if…else if…else statement is also known as if-else-if ladder which is used for multi way decision making.  It is used when there are more than two different conditions.  It tests conditions in a sequence, from top to bottom.  If first condition is true then the associated block with if statement is executed and rest of the conditions are skipped.  If condition is false then then the next if condition will be tested, if it is true then the associated block is executed and rest of the conditions are skipped. Thus it checks till last condition.  Condition is tested only and only when all previous conditions are false.  The last else is the default block which will be executed if none of the conditions are true.  The last else is not mandatory. If there are no default statements then it can be skipped.

if (condition 1) { statement-block1; } else if (condition 2) { statement-block2; } else if (condition 3) { statement-block3; } else if (condition 4) { statement-block4; } else default-statement;

2 – Selections, Mathematical functions & loops

WAP to print if a number is zero or positive or negative

  1. import java.util.*;
  2. class MyProgram{
  3. public static void main (String[] args){
  4. int x;
  5. Scanner sc = new Scanner(System.in);
  6. x = sc.nextInt();
  7. if(x > 0){
  8. System.out.println(" number is a positive");
  9. }
  10. else if(x < 0) {
  11. System.out.println(" number is a negative");
  12. }
  13. else{
  14. System.out.println(" number is a zero");
  15. }
  16. }

WAP to print day name from day number

  1. public class Demo {
  2. public static void main(String[] args) {
  3. int d;
  4. Scanner sc = new Scanner(System.in);
  5. d = sc.nextInt();
  6. if (d == 1 ) System.out.println(“Monday”);
  7. else if (d == 2) System.out.println(“Tuesday“);
  8. else if (d == 3) System.out.println(“Wednesday“);
  9. else if (d == 4) System.out.println(“Thursday“);
  10. else if (d == 5) System.out.println(“Friday“);
  11. else if (d == 6) System.out.println(“Saturday“);
  12. else System.out.println(“Sunday“) ;
  13. }
  14. }

Nested If statement

 A nested if is an if statement that is the target of another if statement.  Nested if statements mean an if statement inside another if statement.  The statement connected to the nested if statement is only executed when - : o Condition of outer if statement is true, and o Condition of the nested if statement is also true.  Note: There could be an optional else statement associated with the outer if statement, which is only executed when the condition of the outer if statement is evaluated to be false and in this case, the condition of nested if condition won't be checked at all