Programming Basics
Programming Basics Procedural or Procedure Oriented Programming (POP) 1)Procedure Oriented Programming contains step by step procedure to execute. 2)Here, the problems get decomposed into small parts and then to solve each part one or more functions are used. 3)Thus in POP approach, the problem is viewed as a sequence of things to be done, such as, input taking, calculating and displaying. 2
Programming Basics For example, Considering that we have to take two values from user and then to display the summation of the inputted values. In POP approach this problem may be decomposed as following, 1)First take an input and put it under one variable, here taking as a. 2)Then take another input and put it under another variable, here taking as b. 3)Now define a variable, such as c, as c = a + b. 4)Now display c. 3
Programming Basics 4
Difference between Compiler and Interpreter Interpreter Compiler Translates program one statement at a time. Scans the entire program and translates it as a whole into machine code. No intermediate object code is generated, hence are memory efficient. Generates intermediate object code which further requires linking, hence requires more memory. Continues translating the program until the first error is met, in which case it stops. Hence debugging is easy. It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. Programming language like Python, Ruby use interpreters. Programming language like C, C++ use compilers. 5
Difference between Compiler and Interpreter 6
Introduction To JAVA
8 Introduction To JAVA Unit # 2 : Introduction to Java What is Java? History Of Java Java Features Java Installation First Java Application Types of Java Applications Java Editions Java Software Components Interview Questions
9 Introduction To JAVA What is JAVA? Java is simple, high performance, object-oriented, robust, secure, multi-threaded, and platform independent programming language to develop software that can be used for gaming, web, business, desktop, database, and other applications. Design goal of Java language project Write once, run anywhere (WORA) – that means java program can run anywhere and on any platform. When java code is compiled it is converted into byte code. Now this byte code is needed to run using JVM, no need of source code and recompilation.
10 Introduction To JAVA History Of Java 1.JAVA was developed by James Gosling and Patrick Naughton from Sun Microsystems Inc in 1991, later(2010) acquired by Oracle Corporation. 2.The design goal of Java is WORA(Write Once Run/Execute Anywhere) it means write a program once and then run this program on multiple operating systems. 3.The first publicly available version of Java (Java 1.0) was released in 1995 and the current of version of Java is Java SE11 released on September, 25th 2018
11 Introduction To JAVA Features of JAVA?
12 Introduction To JAVA Important Features Of Java Simple 1)It does not use header files. 2)Eliminated the use of pointer and operator overloading. 3)Java is easy to learn and familiar because java syntax is just like c++. 4)There is a provision of Automatic Garbage Collection, in which there is no need to remove the unreferenced objects explicitly.
Introduction To JAVA Compiled and Interpreted Usually, a computer language can be either compiled or interpreted. Java integrates the power of Compiled Languages with the flexibility of Interpreted Languages. Java compiler (javac) compiles the java source code into the bytecode. Java Virtual Machine (JVM) then executes this bytecode which is executable on many operating systems and is portable. 13
14 Introduction To JAVA Platform Independent 1)Platform-independent means a program compiled on one machine can be executed on any machine in the world without any change. Java achieves platform independence by using the concept of the BYTE code. 2)The Java compiler never converts the source code to machine code like that of the C/C++ compiler. Instead, it converts the source code into an intermediate code called the byte code and this byte code is further translated to machine-dependent form by another layer of software called JVM (Java Virtual Machine). 3)Therefore, JVM can execute bytecode on any platform or OS on which it is present, regardless of the fact that on which machine the bytecode was generated. 4)This is where the “Write Once, run anywhere” (WORA) slogan for Java comes in, which means that we can develop applications on one environment (OS) and run on any other environment without doing any modification in the code.
15 Introduction To JAVA
Introduction To JAVA Portable You can run Java bytecode on any hardware that has a compliant JVM which can convert the bytecode according to that particular machine. In Java, the size of the primitive data types is machine- independent, which were dependent in the case of C/C++. So, these provisions make Java programs portable among different platforms such as Windows, Unix, Solaris, and Mac. Moreover, any changes and updates made in Operating Systems, Processors and System resources will not enforce any changes in Java programs. 16
17 Introduction To JAVA Object Oriented Programming Language 1)Object oriented programming is a way of organizing programs as collection of objects, each of object represents an instance of a class. 2)Java programs also organizing collection of classes and objects so Java is called as object oriented programming language
18 Introduction To JAVA Robust Robust means inbuilt capabilities to handle errors/exceptions. Java is robust because of following 1)Built-in Exception handling. 2)Strong type checking i.e. all data must be declared an explicit type. 3)Automatic garbage collection. 4)First checks the reliability of the code before Execution etc.
19 Introduction To JAVA Secure Java programs run within the JVM which protects from unauthorized access to system resources. That’s why several security flaws like stack corruption or buffer overflow is impossible to exploit in Java.
20 Introduction To JAVA Multithreading Java supports multithreading. Multithreading is a feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU.
21 Introduction To JAVA Distributed This feature in Java gives the advantage of distributed programming, which is very helpful when we develop large projects. Java helps us to achieve this by providing the concept of RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans). In Java, we can split a program into many parts and store these parts on different computers. A Java programmer sitting on a machine can access another program running on the other machine. Java comes with an extensive library of classes for interacting, using TCP/IP protocols such as HTTP and FTP, which makes creating network connections much easier than in C/C++. It also enables multiple programmers at many locations to work together on a single project.
22 Introduction To JAVA Architectural Neutral Architectural neutral means that the program written on one platform is independent of other platforms and can run on any other platform without recompiling them. Byte-code is not dependent on any machine architecture and Java Virtual Machine (JVM) can easily translate bytecode into a machine-specific code. Dynamic The process of allocating the memory space to the input of the program at a run-time is known as dynamic memory allocation. In Java memory allocation happened at run-time with the help of 'new' operator. So Java is dynamic
23 Introduction To JAVA High performance Java provides high performance with the use of “JIT – Just In Time compiler”, in which the compiler compiles the code on-demand basis, that is, it compiles only that method which is being called. This saves time and makes it more efficient. Java architecture is also designed in such a way that it reduces overheads during runtime. The inclusion of multithreading enhances the overall execution speed of Java programs. Bytecodes generated by the Java compiler are highly optimized, so Java Virtual Machine can execute them much faster.
24 Introduction To JAVA Components Of Java Software Java Development Kit (JDK) Java Development Kit contains two parts. One part contains the utilities like javac, debugger and some jar files which helps in compiling the source code (.java files) into byte code (.class files) and debug the programs. The other part is the JRE, which contains the utilities like java which help in running/executing the byte code. If we want to write programs and run them, then we need the JDK installed.
25 Introduction To JAVA Java Run-time Environment (JRE) Java Run-time Environment helps in running the programs. JRE contains the JVM, the java classes/packages and the run-time libraries. If we do not want to write programs, but only execute the programs written by others, then JRE alone will be sufficient.
26 Introduction To JAVA Java Virtual Machine (JVM) Java Virtual Machine is important part of the JRE, which actually runs the programs (.class files), it uses the java class libraries and the run-time libraries to execute those programs. Every operating system(OS) or platform will have a different JVM.
27 Introduction To JAVA Just In Time Compiler (JIT) JIT is a module inside the JVM which helps in compiling certain parts of byte code into the machine code for higher performance.
28 Introduction To JAVA
29 Introduction To JAVA Editions Of Java Software JavaSE (Java Standard/Software Edition) JavaSE is mainly used to create applications for Desktop environment. It consist all the basics of Java the language, variables, primitive data types, Arrays, Streams, Strings Java Database Connectivity(JDBC) and much more.
30 Introduction To JAVA JavaEE(Java Enterprise Edition) The enterprise edition of Java has a much larger usage of Java, like development of web applications, networking, server side scripting and other various web based applications. JavaEE uses many components of JavaSE, as well as, has many new features of it’s own like Servlets, JavaBeans, Java Message Services etc,.
31 Introduction To JAVA JavaME (Java Micro/Mobile Edition) This version of Java is mainly concentrated for the applications running on embedded systems, mobiles wireless devices, set top boxes etc. Old Nokia phones, which used Symbian OS, used this technology.
First Java Application
33 First Java Application Steps To Write First Java Program Step 1:Decalre the class Every java application must have at least one class definition that consists of class keyword followed by class name. public class FirstJavaProgram { }
34 First Java Application Step 2: Declare the main() method To execute the above class JVM need one entry point in the class that entry point is main()method having signature as shown below public static void main(String[] args) { }
35 First Java Application public – access modifier, meaning global visibility static – the method can be accessed straight from the class, we don’t have to instantiate an object to have a reference and use it void – means that this method doesn’t return a value main – the name of the method, that’s the identifier JVM looks for when executing a Java program args parameter, it represents the values received by the method.
36 First Java Application Step 3: Write logic Write some logic or statement to generate simple response as shown below System.out.println("This is my first program in java");
37 First Java Application
38 First Java Application Step 4:Save The File We should always save the file same as the public class name. In our program, the public class name is FirstJavaProgram, that’s why our file name should be FirstJavaProgram.java.
39 First Java Application Step 5: Compile The Program We will compile the program. For this, open command prompt (cmd) on Windows type the following command and hit enter. javac FirstJavaProgram.java Stpe 6: Execute The Program After compilation the .java file gets translated into the .class file(byte code). Now we can run the program. To run the program, type the following command and hit enter: java FirstJavaProgram
40 First JAVA Application Java Compilation And Execution 1)In the Java programming language, all source code is first written and save with the .java extension. 2)After compilation, .class files are generated by javac compiler. 3) A .class file contain byte code that is not natural to your processor, this byte code convert into processor understandable code by JVM
41 First JAVA Application Java Compilation and Execution
Naming Conventions in Java
Naming Conventions In Java Identifiers A name in the program is an identifier it may be class name or method name, variable name or label name. Example Class Test{ public static void main(String[] args) { int x=10 System.out.println(x); } 43
Naming Conventions In Java Rules for defining Identifiers 1)Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). 2)Identifiers cannot start with a number 3)After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers. 4)In practice, there is no limit to the number of characters an identifier can contain. 5)You can't use a Java keyword as an identifier. 6)Identifiers in Java are case-sensitive; foo and FOO are two different identifiers. 44
Naming Conventions In Java Coding standards for classes Usually class name should be noun. Should starts with upper case letter and if it contain multiple words every inner words also should start with capital letters. Example: String StringBuffer NumberFormat CustomerInformation 45
Naming Conventions In Java Coding standards for Interfaces Usually interface named should be adjective, starts with capital letters and if it contains multiple words, every inner word also should starts with capital letter. Example: Runnable Serializable Clonable Movable Transferable Workable 46
Naming Conventions In Java Coding standards with methods Values should be either verbs or verb + noun combination. Starts with lower case and every inner words starts with upper case(this convention is also called camel case convention). Example: getName(), getMessage(), toString(), show(), display(). 47
Naming Conventions In Java Coding standards for variables Usually the variable starts with noun and every inner word should start with upper case i.e camel case convention. Example: name, rollNo, bandwidth, totalNumber. 48
Naming Conventions In Java Coding standards for constants It should be noun, it should contain only upper case letters and works are separated with underscores. Example: MAX_SIZE, MIN_PRIORITY, COLLEGE_NAME. 49
Data types, Literals and Variables in Java
Data types in Java Data type In computer science, a data type is an attribute of data that tells the compiler or interpreter how the programmer aims to use the data. Java Data Types 1)Primitive Data Types 2)Non-Primitive DataTypes Primitive Data Types As the name suggests, the programming language pre-defines the primitive data types. Primitive types are the most basic data types available in Java. There are 8 primitive data types in Java: byte, char, short, int, long, float, double and boolean. Primitive data types have a constraint that they can hold data of the same type and have a fixed size. 51
Data types in Java 52
Data types in Java Non-Primitive Data Types/ Referenced Data Types 1)The term non-primitive data type means that these types contain “a memory address of the variable”. 2)In contrast to primitive data types, which are defined by Java, non-primitive data types are not defined or created by Java but they are created by the programmers. They are also called Reference data types because they cannot store the value of a variable directly in memory. 3)Non-primitive data types do not store the value itself but they store a reference or address (memory location) of that value. 53
Data types in Java Java Integers It can hold whole numbers such as 196, -52, 4036 etc. Java supports four different types of integers These are: 54
Data types in Java 55
Data types in Java 56
Floating Point Numbers Floating Representation 57
Single precision floating point number Single precision uses 32 bit to represent a floating point number. First bit represent the sign of the number, negative or positive. Next 8 bits are used to store the exponent of the number. This exponent can be signed 8-bit integer ranging from -127 – 128 of signed integer (0 to 255). And the left 23 bits are used to represent the fraction part and are called fraction bits. 8 exponent bits provide us with the range and 23 bits provide us with the actual precision. 58
Double precision floating point number Double precision uses 64 bits to represent a value. First bit is used for the same purpose as in single point precision i.e., represents sign of the number. Next 11 bits are used to denote exponent, which provide us with the range, and has 3 more bits than single precision, so it is used to represent a wider range of values. Next 52 bits are used to represent the fractional part which is 29 bits more than binary32 bit representation scheme. So it has a greater precision than single precision. 59
Data types in Java 60 Floating-Point Literals in Java Here, datatypes can only be specified in decimal forms and not in octal or hexadecimal form.
Data types in Java Java Characters A character is used to store a ‘single’ character. A single quote must surround a character. The valid Character type is char. In Java, a character is not an 8-bit quantity but here character is represented by a 16-bit Unicode. 61 Syntax char myChar = ’A’ ; Size 2 bytes(16 bits) Values A single character representing a digit, letter, or symbol. Default Value ‘u0000’ (0) Range u0000’ (0) to ‘uffff’ (65535)
Data types in Java Char Literals in Java These are the four types of char Single Quote Java Literal can be specified to a char data type as a single character within a single quote. char ch = 'a'; Char as Integral A char literal in Java can specify as integral literal which also represents the Unicode value of a character. Furthermore, an integer can specify in decimal, octal and even hexadecimal type, but the range is 0-65535. char ch = 062; 62
Data Types in Java Unicode Representation Char literals can specify in Unicode representation ‘uxxxx’. Here XXXX represents 4 hexadecimal numbers. char ch = 'u0061';// Here /u0061 represent a. Escape Sequence Escape sequences can also specify as char literal. 63
Data types in Java boolean • boolean data type represents one bit of information as either true or false. i.e. there is only two possible value true or false. Internally, JVM uses one bit of storage to represent a boolean value. • It is generally used to test a particular conditional statement during the execution of program. • boolean data type takes zero bytes of memory. • Default value is false. For example: boolean b = false; 64
Variables in Java Variables in Java A variable in Java is a kind of container that contains the value during program execution. Variable is a basic unit of storage in a program that represents reserved storage locations, whose values can be manipulated during the execution of a program. Declaration of a Variable To declare the variable, we must specify the data type followed by the unique name of the variable. Syntax: dataType variableName Example: double payRate ; 65
Variables in Java Initialization of a Variable Syntax: variableName = value ; Example: payRate = 2500; Combining the declaration and initialization, we can write dataType variableName = value ; Example: double area = 378.87 ; 66
Variables in Java 67
Variables in Java Naming conventions for variables 1)The variable names cannot contain white spaces, for example, long dist ance = 1000; is invalid because the variable name has a space in it. 2)A variable name can begin with a special character dollar ($) and underscore ( _ ). 3)The first letter of a variable cannot be a digit. 4)A variable name should begin with a lowercase letter, for example, int number. For lengthy variable names having more than one word, we can use camelCase, for example, int salaryPerDay; float rateOfInterest; ,etc. are valid. 5)We cannot use keywords like int, for, while, class, etc as a variable name. 6)Variable names are case-sensitive in Java. 68
Type Promotion in Java Type Promotion in Java There are several type promotion rules in Java that are followed while evaluating expressions- 1)All byte, short and char values are promoted to int. 2)If any operand is long then the expression result is long. i.e. whole expression is promoted to long. 3)If any operand is a float then the expression result is float. i.e. whole expression is automatically promoted to float. 4)If any operand is a double then the expression result is double. i.e. whole expression is promoted to double in Java. 69
Type Promotion in Java When one of the operand is double. int i = 30; double d = 2.5; double result = i * d; When one of the operand is float. short s = 4; int i = 30; float f = 6.75f; float result = (s+i) * f; 70
Type Casting in Java
Type Casting in Java What is Type Casting or Type Conversion Type Conversion or Type Casting is the process of converting a variable of one predefined type into another. If these data types are compatible with each other, the compiler automatically converts them and if they are not compatible, then the programmer needs to typecast them explicitly. 72
Type Casting in Java Types of Type Conversion 1)Implicit Type Conversion 2)Explicit Type Conversion 73
Type Casting in Java Implicit Type Conversion Implicit Type Conversion or Automatic type conversion is a process of automatic conversion of one data type to another by the compiler. This process is also called Widening Conversion because the compiler converts the value of narrower (smaller size) data type into a value of a broader (larger size) data type without loss of information. The implicit data type conversion is possible only when 1)The two data types are compatible with each other. 2)There is a need to convert a smaller or narrower data type to the larger type size. For example, the compiler automatically converts byte to short because the byte is smaller ( 8 bits ) or narrower than short ( 16 bits ). 74
Type Casting in Java 75
Type Casting in Java Explicit Type Conversion The Explicit Type Conversion is a process of explicitly converting a type to a specific type. We also call it Narrowing Conversion. The typecasting is done manually by the programmer, and not by the compiler. We need to do explicit or narrowing type conversion when the value of a broader (higher size) data type needs to be converted to a value of a narrower (lower size) data type. For example, double data type explicitly converted into int type. 76
Type Casting in Java The following is the syntax of typecasting in Java (type) expression; Where type is a valid data type to which the conversion is to be done. For example, if we want to make sure that the expression (x / y + 5) evaluates to type float, we will write it as, (float)(x / y +5); 77
Type Casting in Java 78
Type Casting in Java 79
Operators In Java
Operators in Java In computer programming, an operator is a special symbol that is used to perform operations on the variables and values. The operators represent the operations (specific tasks) and the objects/variables of the operations are known as operands. 81
Operators in Java Types of Operators 82
Operators in Java Arithmetic Operators Java provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division, and the remainder which are +, -, *, /, and % respectively. Each of these is a binary operator that is, it requires two values (operands) to perform calculations. 83
Operators in Java Relational Operators Java provides 6 relational operators for comparing numbers and characters. But, relational operators do not work with strings. After the comparison, they return the result in boolean datatype. If the comparison is true, the relational operator results in true, otherwise false. 84
Operators in Java 85
Operators in Java Logical Operators Logical operators are also known as conditional operators. These operators are used for evaluating one or more boolean expression, for complex decision-making. They also return a boolean value (true or false). There are three types of logical or conditional operators in Java are && (Logical-AND), || (Logical-OR) and ! (Logical NOT).types of logical or conditional operators In this, && (Logical-AND) and || (Logical-OR) operators are the binary logical operators that work on two operands or expressions, while ! (Logical NOT) is a unary logical operator which works on single operand or expression. 86
Operators in Java 87
Operators in Java 1) A Logical-AND (&&) evaluates the left side of the operation first (operand one), and if it resolves to false, the && operator doesn't bother looking at the right side of the expression (operand two) since the && operator already knows that the complete expression can't possibly be true. 2) The Logical-OR(||) operator is similar to the && operator, except that it evaluates to true if EITHER of the operands is true. 3) If the first operand in an OR operation is true, the result will be true, so the short-circuit || doesn't waste time looking at the right side of the equation. 4) If the first operand is false, however, the short-circuit || has to evaluate the second operand to see if the result of the OR operation will be true or false. 88
Operators in Java The logical NOT operator, which is written as ! , is a unary operator that works on a single operand or expression. The Logical NOT operator (!) negates or reverses the truth value of its operand. That is if the expression is true, then !expression is false and vice- versa. ! (9 != 0) //results into false because 9 is non-zero(i.e., true). ! (6 > 2) //results into false because the expression 6 > 2 is true. ! (4 > 10) //results into true because the expression 4 > 10 is false. 89
Operators in Java Bitwise Operators in Java The Bitwise operators manipulate the individual bits of a number. The bitwise operators work with the integer types that is, byte, short, int, and long types. Java provides 4 bitwise operators: 90
Operators in Java 91
Operators in Java Bitwise NOT( ~ ) The Bitwise NOT is represented by the symbol (~) . Bitwise NOT is an unary operator and inverts all the bits represented by its operand. That is, 0s become 1s and 1s become byte a = 3;//00000011 byte b = (byte)~a;//11111100 System.out.println("Value of b = "+b);//-4 92
Operators in Java 93
Operators in Java The Bitwise AND Operator (&) The bitwise AND operator, &, produces a 1 bit if both the operands are also 1. A zero is produced in all the other cases. Example 00101010 42 &00001111 15 _________ 00001010 10 94
Operators in Java The Bitwise OR Operator The bitwise OR operator, |, combines bits such that if either of the bits in the operands is 1, then the resultant bit is 1. Example 00101010 42 |00001111 15 _________ 00101111 47 95
Operators in Java The Bitwise XOR Operator The bitwise XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1. Otherwise, the result is zero. Example 00101010 42 ^00001111 15 _________ 00100101 37 96
Operators in Java Java ternary(?) Operator Ternary (three-way) operator can replace certain types of if-then-else statements. general form expression1 ? expression2 : expression 3 Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. int i, k; i = 10; k = i < 0 ? -i : i; // get absolute value of i System.out.println("Absolute value of " + i + " is " + k);//10 i = -10; k = i < 0 ? -i : i; // get absolute value of i System.out.println("Absolute value of " + i + " is " + k);//-10 97
Operators in Java Java instanceof Operator The instanceof operator in Java, used only for the object reference variables. This operator basically checks whether the object is of a specific type (class or interface type). general form (Object reference variable) instanceof (class/interface type) String str_name = "James"; boolean res = str_name instanceof String; System.out.println(res); 98
Control Statements in Java
Control Statements in Java Control Statements in Java The statements those who control the order of execution of a program are known as control statements Types of control statements 1)Selection/Decision making Statements Using these statements, a piece of code would be executed only if a certain condition(s) is true. 2)Iteration statements Using these statements to iterate a block of code repeatedly until the condition is false 3) Jump statements Using these statements to skip the statements and come-out from those. 100
Control Statements in Java 101
Control Statements in Java The if-else control statement The if-else statement is used to choose & execute any one action among two. Syntax if(condition){ // group of programming statements } else{ // group of programming statements } Braces in the if-else and other control statements are optional if we used only one statement for every action If the condition present inside the parentheses is true, if-block is executed. After execution of if-block, program control skips else-block and jumps directly to the statements after else-block. If the condition inside the parenthesis is false, else-block is executed by skipping if-block 102
Control Statements in Java 103
Control Statements in Java if statement (if without else statement) It is possible to use if statement without the else statement. Syntax if(condition){ // group of // programming // statements } If the condition inside parentheses is true, if-block is executed. After execution of if-block, program control executes statements after it. If the condition inside the parenthesis is false, if-block is skipped, and statements after it are executed. 104
Control Statements in Java 105
Control Statements in Java Nested if statement In Java programming, it is possible to place if control statement inside another if-block or else-block. if(condition1){ // outer if-block if(condition2){ block1 } } else { // outer else-block if(condition3){ block2 } } In the above example, if condition1 becomes true, program control enters into outer if-block. Then it checks for condition2. If condition2 is true, block1 is executed. After execution of block1, control is transferred directly to the statement after the outer else- block. If condition1 becomes false, program control enters into outer else-block skipping outer if- block. Then it checks for condition3. If condition3 is true, block2 is executed. After execution of block2 and outer else-block control is transferred directly to statement after 106
Control Statements in Java 107
Control Statements in Java 108 Program to find bigger number among three given number if(a>b){//’a’ is bigger if(a>c)//’a’ is already bigger than ‘b’ so the comparison with ‘c’ only ‘a’ is bigger else ‘c’ is bigger }//outer if else{ if(b>c)//compare to ‘a’ ‘b’ is bigger control comes to here. Comparison with ‘c’ only ‘b’ is bigger else ‘c’ is bigger } a=12, b=14, c=11
Control Statements in Java 109 Program to find out the given year is leap year or not? Logic: A centennial (divisible by 100) year is leap if it is divisible by 400, and a non-centennial year is leap if it is divisible by 4. if(year %100!=0){ if(year%4==0) leap year else not a leap year } else{ if(year%400==0) leap year else not a leap year } Solution with if-else -------------------------- if(year%100!=0 && year %4==0 || year%400==0) leap year else not a leap year
Control Statements in Java 110 Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count. public int luckySum(int a, int b, int c) { } For example, luckySum(1, 2, 3) → 6 luckySum(1, 2, 13) → 3 luckySum(1, 13, 3) → 1 luckySum(13, 5, 3) → 0
Control Statements in Java 111 luckySum solution public int luckySum(int a, int b, int c) { if (a == 13) return 0; else if (b == 13) return a; else if (c == 13) return a + b; else return a + b +c; }
Control Statements in Java 112 When bachelor's get together for a party, they like to have beers. A bachelor party is successful when the number of beers is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of beers. Return true if the party with the given values is successful, or false otherwise. public boolean beerParty(int beers, boolean isWeekend) { } beerParty(30, false) → false beerParty(50, false) → true beerParty(70, true) → true beerParty(30, true) → false
Control Statements in Java 113 beerParty solution public boolean beerParty(int beers, boolean isWeekend) { if (isWeekend == true && beers >= 40) return true; if (!(isWeekend) && beers >=40 && beers<= 60) return true; else return false; }
Control Statements in Java 114 We are having a party with amounts of tea and candy. Return the int outcome of the party encoded as 0=bad, 1=good, or 2=great. A party is good (1) if both tea and candy are at least 5 rating. However, if either tea or candy is at least double the amount of the other one, the party is great (2). However, in all cases, if either tea or candy is less than 5 rating, the party is always bad (0). public int teaParty(int tea, int candy) { } teaParty(6, 8) → 1 teaParty(3, 8) → 0 teaParty(20, 6) → 2
Control Statements in Java 115 teaParty solution public int teaParty(int tea, int candy) { if (tea < 5 || candy < 5) return 0; if ((tea >= 2 * candy) || (candy >= 2 * tea)) return 2; else return 1; }
Control Statements in Java The if-else-if ladder statement The if-else-if ladder is a very common programming constructs in Java, which is also called the if-else-if staircase because of its appearance. We can use many if-else-if statements in our program. The general form or syntax of the if-else-if ladder statement is: if( expression1) statement1 ; else if(expression2) statement2; . . else statement3; 116
Control Statements in Java 117
Control Statements in Java The switch statement In Java programming, the switch statement is used to make a specific selection from multiple cases. Syntax switch(expression){ case constant_value_1 : statements to be executed; break; case constant_value_2 : statements to be executed; break; case constant_value_N : statements to be executed; break; case default : statements to be executed; } 118
Control Statements in Java 1) In a switch statement, the expression inside switch’s left & right parenthesis is executed first. 2) If any case matches the expression value, program control jumps directly to that case and statements of that case are executed. 3) If expression value does not match with any case, then program control jumps directly to the default case and statements of default case are executed. 119
Control Statements in Java 120
Control Statements in Java 121
Control Statements in Java The for loop Syntax for(initialization;condition;update){ // programming // statements } The for loop consists of three expressions called initialization, condition & update and its body (statements inside curly braces). 122
Control Statements in Java 123
Control Statements in Java The while loop Same as for loop, while loop is used to execute specific part of the program repeatedly. Syntax while(condition){ // programming // statements } 124
Control Statements in Java 125
Control Statements in Java The do-while loop Same as for loop and while loop, do-while loop is also used to execute specific part of the program repeatedly. The only difference is that the body of do-while loop is executed at least once even if the condition is false. Syntax do{ // programming // statements }while(condition); 126
Control Statements in Java 127
Control Statements in Java The break statement The statement that is used to break/stop the flow of loops & switch statement is known as break statement. Inside the loop, break statement terminates the loop execution when it is encountered. Inside switch statement, break statement is used to jump out of the switch statement instantly when it is encountered. Syntax break; Java Programming Language break Statement Working in for, while and do-while loops After terminating a loop by using the break statement, program control is transferred immediately to the statement after the loop. 128
Control Statements in Java 129
Control Statements in Java The continue statement The continue statement forces loop to skip statements written after it & continue next execution of the loop. Syntax continue; Note If the continue statement is encountered in the for loop, program control jumps directly to the update expression. If the continue statement is encountered in the while & do-while loops, program control jumps directly to the condition. 130
Control Statements in Java 131
Type Promotion in Java 132
Arrays In Java
Arrays In Java 1) In Java array is an object which store multiple variables of the same type. It can hold primitive types as well as object references. Since array is an object, it is created during runtime .The array length is fixed. 2) Array is an index based data structure so it allow random access to elements, they store. Indices start with '0' 134
Arrays In Java Features of an Array 1)Array is an object so we can find the length of the array using attribute 'length'. 2)Array is an ordered and each have an index beginning from '0' for the first element. 3)Arrays can store primitives as well as objects. But all must be of a single type in one array instance. 4)Just like other variables so can used as method arguments. 5)The size of an array must be specified by an int value. 135
Arrays In Java 136
Arrays In Java Array Declaration The declaration of array states the type of the element that the array holds followed by the square braces and identifier which indicates the identifier is array type. Example Declaring an array which holds elements of integer type. 137
Arrays In Java Different way of declaring an array 138
Arrays In Java Note 139
Arrays In Java 140
Arrays In Java Note 141
Arrays In Java 142
Arrays In Java Initialization of an array 143
Arrays In Java 144
Arrays In Java 145
Arrays In Java 146
Arrays In Java Accessing elements from an array by using index value After the array is created, its elements can be accessed by their index. The index is a number placed inside square brackets which follow the array name. Example, String[] names = {"Jane", "Thomas", "Lucy", "David"}; System.out.println(names[0]); System.out.println(names[1]); System.out.println(names[2]); System.out.println(names[3]); 147
Arrays In Java Accessing elements from an array by using for each loop J2SE 5 introduces special type of for loop called foreach loop to access elements of array. Using foreach loop you can access complete array sequentially without using index of array. Example, int[] arr = {10, 20, 30, 40}; for(int x : arr){ System.out.println(x); } 148
Arrays In Java Accessing elements from an array by using basic for loop Example, String[] planets = { "Mercury", "Venus", "Mars", "Earth", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" }; for (int i=0; i < planets.length; i++) { System.out.println(planets[i]); } 149
Arrays In Java Anonymous arrays You can create an array without specifying any name such arrays are known as anonymous arrays. Since it doesn’t have name to refer you can use it only once in your program. Generally, anonymous arrays are passed as arguments to methods. You can create an anonymous array by initializing it at the time of creation. For example, new int[] { 1254, 5452, 5743, 9984}; //int array new String[] {"Java", "JavaFX", "Hadoop"}; //String array 150
Arrays In Java public class AnonymousArray { public static void arrayToUpperCase(String [] array) { for(int i=0; i< array.length; i++) { char[] ch = array[i].toCharArray(); for(int j=0; j<ch.length; j++){ ch[j] = Character.toUpperCase(ch[j]); } System.out.println(new String(ch)); } } public static void main(String args[]) { arrayToUpperCase(new String[] {"Krishna", "Vishnu", "Dhana", "Rupa", "Raja", "Kavya"}); }} 151
Arrays In Java Two-dimensional Arrays The Two Dimensional Array in Java programming language is nothing but an Array of Arrays. In Java Two Dimensional Array, data stored in row and columns, and we can access the record using both the row index and column index 152
Arrays In Java Example, Two dimensional array: int[][] twoDarr = new int[10][20]; Three dimensional array: int[][][] threeDarr = new int[10][20][30]; The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements. 153
Arrays In Java Declaration of 2D array Data_Type[][] Array_Name; Example : int [][] anIntegerArray; Create Two dimensional Array in Java In order to create a two dimensional array in Java, we have to use the New operator as we shown below: Data_Type[][] Array_Name = new int[Row_Size][Column_Size]; Example : anIntegerArray = new int[3][4]; It is a 2-dimensional array, that can hold a maximum of 12 elements, 154
Arrays In Java 155
Arrays In Java Declaration and Initialization of 2D array Syntax data_type[][] array_name = { {valueR1C1, valueR1C2, ....}, {valueR2C1, valueR2C2, ....} }; For example, int[][] arr = {{1, 2}, {3, 4}}; 156
Arrays In Java Retrieve elements from 2D arrays standard method int[][] a={{10,20},{30,40}};//declaration and initialization System.out.println("Two dimensional array elements are"); System.out.println(a[0][0]); System.out.println(a[0][1]); System.out.println(a[1][0]); System.out.println(a[1][1]); 157
Arrays In Java Retrieve elements from 2D array by using for loop int[][] a={{10,20},{30,40},{50,60}};//declaration and initialization System.out.println("Two dimensional array elements are"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++){ System.out.println(a[i][j]); } } 158
Arrays In Java Dynamically passing row and column sizes Scanner sc=new Scanner(System.in); System.out.println("Enter Row length of an array : "); int row=sc.nextInt(); System.out.println("Enter column length of an array : "); int column=sc.nextInt(); int a[][]=new int[row][column];//declaration 159
Arrays In Java System.out.print("Enter " + row*column + " Elements to Store in Array :n"); for (int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ a[i][j] = sc.nextInt(); } } 160
Arrays In Java System.out.print("Elements in Array are :n"); for (int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ System.out.println("Row ["+i+"]: Column ["+j+"] :"+a[i][j]); } } 161
Arrays In Java Jagged Array in Java Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays. int arr[][] = new int[2][]; // Declaring 2-D array with 2 rows // Making the above array Jagged arr[0] = new int[3]; // First row has 3 columns arr[1] = new int[2]; // Second row has 2 columns 162
Arrays In Java // Initializing array int count = 0; for (int i=0; i<arr.length; i++) for(int j=0; j<arr[i].length; j++) arr[i][j] = count++; // Displaying the values of 2D Jagged array System.out.println("Contents of 2D Jagged Array"); for (int i=0; i<arr.length; i++) { for (int j=0; j<arr[i].length; j++) System.out.print(arr[i][j] + " "); System.out.println(); } 163
Abstraction In Java In object oriented programming abstraction is a process of providing functionality to the users by hiding its implementation details from them In other words, the user will have just the knowledge of what an entity is doing instead of its implementation 164
Abstraction In Java Real life example of Abstraction is ATM Machine; All are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about ATM. 165
Abstraction In Java Advantages of Abstraction 166
Abstraction In Java How to Achieve Abstraction in Java? In Java, we can achieve Data Abstraction using Abstract class and Interface Interface allow 100% abstraction(complete abstraction). Interface allow you to abstract the implementation completely Abstract class allow 0 to 100% abstraction (partial to complete abstraction)because abstract class can contain concrete methods that have the implementation which results in a partial abstraction 167
Abstraction In Java In Java programming we have two types of classes they are 1)Concrete class 2)Abstract class A concrete class is one which is containing fully defined methods or implemented method. class Helloworld{ void display(){ System.out.println("Good Morning........"); } } 168
Abstraction In Java Abstract class A class that is declared with abstract keyword, is known as abstract class. An abstract class is one which is containing some defined method and some undefined method. In java programming undefined methods are known as un-Implemented, or abstract method. Syntax abstract class className{ ...... } Example abstract class A{ ..... 169
Abstraction In Java Abstract method An abstract method is one which contains only declaration or prototype but it never contains body or implementation. In order to make any method as abstract whose declaration is must be predefined by abstract keyword. The declaration of an abstract method must end with a semicolon; Syntax abstract ReturnType methodName(List of formal parameter); Example abstract void Bike(); 170
Abstraction In Java Rules for Using Abstract Class in Java 1)We can declare an abstract class using the abstract keyword. 2)It may have abstract as well as concrete (non-abstract) methods. 3)An abstract class can have static methods. 4)An abstract class can also have constructors. 5)It can have final methods. If we declare the method as final inside the abstract class then the subclass can not change the body of the method. 171
Abstraction In Java 6) We can’t instantiate or create an object of an abstract class. 7) A class derived from the abstract parent class must implement each method that is declared as abstract in the parent class. Otherwise, there will be a compilation error. 8) If the derived class does not implement all the abstract methods of an abstract parent class, then the derived class must also declare itself as abstract. 172
Abstraction In Java Why do we need Abstract Classes in Java? We want to create a class that just declares the methods without providing a complete implementation of every method. And, we want that this method(s) is shared by all of its child classes, and all the implementation details will be filled by these subclasses. Let’s take the example of a banking application or software. Suppose we have a class BankAccount that has a method deposit() and withdraw() and the subclasses of it like SavingsAccount, CurrentAccount, FixedDepositAccount, etc. Since the process of deposit and withdrawal differs from one account to another, there is no point to implement these two methods in the parent class BankAccount. This is because every child class must override these methods and provide an implementation of them. 173
Abstraction In Java 174
Abstraction In Java Interface In Java 1)In Java, an interface is a blueprint or template of a class used to achieve 100%abstraction. 2)When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. 3)There can be only abstract methods in an interface. 4)If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract. 175
Abstraction In Java Syntax to create an interface interface interface-name{ //abstract methods } Example interface Animal{ public void eat(); public void travel(); } 176
Abstraction In Java Why we do use interface? 177
Abstraction In Java Properties of a Java Interface 1)An interface is implicitly abstract. While declaring an interface, you do not need to use the keyword abstract. 2)Each method of an interface is implicitly public and abstract, so we need not use the public and abstract keyword while declaring methods inside an interface. The following five method declarations are legal and identical a)void bounce(); b)public void bounce(); c)abstract void bounce(); d)public abstract void bounce(); e)abstract public void bounce(); 178
Abstraction In Java 3) All variables defined in an interface are public, static, and final. In other words, interfaces can declare only constants, not instance variables. Legal interface constants declarations a) public int x = 1; // Looks non-static and non-final, // but isn't! b) int x = 1; // Looks default, non-final, // non-static, but isn't! c) static int x = 1; // Doesn't show final or public d) final int x = 1; // Doesn't show static or public e) public static int x = 1; // Doesn't show final f) public final int x = 1; // Doesn't show static g) static final int x = 1 // Doesn't show public 179
Abstraction In Java 180
Abstraction In Java 4) An interface can extend one or more other interfaces. 5) A class can extend only one class (no multiple inheritance), but it can implement one or more interfaces. 181
Abstraction In Java 182 1) class Foo { } class Bar implements Foo { } 2) interface Baz { } interface Fi { } interface Fee implements Baz { } 3) class Foo { } interface Zee implements Foo { } 4) class Foo interface Zoo extends Foo { }
Abstraction In Java 5) interface Fi { } interface Boo extends Fi { } 6) class Toon extends Foo, Button { } 7) class Zoom implements Fi, Baz { } 8) interface Vroom extends Fi, Baz { } 9)class Yow extends Foo implements Fi { } 183
Abstraction In Java How interface is different from class ? 1)You can not instantiate an interface. 2)It does not contain any constructors. 3)All methods in an interface are abstract. 4)Interface can not contain instance fields. Interface only contains public static final variables. 5)Interface is can not extended by a class; it is implemented by a class. 6)Interface can extend multiple interfaces. It means interface exhibit the functionality multiple inheritance 184
Abstraction In Java Implementing Interfaces in Java A class implementing an interface it means that the class agrees to perform the specific behaviors of the interface. Unless a class is declared as abstract, it should perform all the behaviors of the interface. In order to implement an interface, a class uses the implements keyword. public class Ball implements Bounceable { public void bounce() { } public void setBounceFactor(int bf) { } } 185
Abstraction In Java When we use abstract and when Interface If we do not know about any things about implementation just we have requirement specification then we should be go for Interface If we are talking about implementation but not completely (partially implemented) then we should be go for abstract Why interface have no constructor ? Because, constructor are used for eliminate the default values by user defined values, but in case of interface all the data members are public static final that means all are constant so no need to eliminate these values. Other reason because constructor is like a method and it is concrete method and interface does not have concrete method it have only abstract methods that's why interface have no constructor. 186
Abstraction In Java 187
Abstraction In Java 188
Abstraction In Java Marker or tagged interface An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation. Example //Way of writing Serializable interface public interface Serializable { } 189
Abstraction In Java New features added in interfaces from JDK 8 version 1) Java 8 allows the interfaces to have default and static methods. Why Default methods? Classes such as A, B, C and D implements an interface XYZ Interface. If we add a new method to the XYZ Interface, we have to change the code in all the classes(A, B, C and D) that implements this interface. Here, we have only four classes that implements the interface which we want to change but imagine if there are hundreds of classes implementing an interface then it would be almost impossible to change the code in all those classes. This is why in java 8, we have a new concept “default methods”. These methods can be added to any existing interface and we do not need to implement these methods in the implementation classes mandatorily, thus we can add these default methods to existing interfaces without breaking the code. 190
Abstraction In Java Why static methods? Static methods in interfaces are similar to the default methods except that we cannot override these methods in the classes that implements these interfaces. 191
Abstraction In Java Interface with default method interface MyInterface{ /* This is a default method so we need not * to implement this method in the implementation * classes */ default void newMethod(){ System.out.println("Newly added default method"); } /* Already existing public and abstract method void existingMethod(String str); } 192
Abstraction In Java Interface with static method interface MyInterface{ default void newMethod(){ System.out.println("Newly added default method"); } /* This is a static method. Static method in interface is static void anotherNewMethod(){ System.out.println("Newly added static method"); } //Already existing public and abstract method void existingMethod(String str); } 193
Abstraction In Java Default Method and Multiple Inheritance The multiple inheritance problem can occur, when we have two interfaces with the default methods of same signature. Lets take an example. interface MyInterface{ default void newMethod(){ System.out.println("Newly added default method"); } void existingMethod(String str); } interface MyInterface2{ default void newMethod(){ System.out.println("Newly added default method"); }void disp(String str); } How to solve this issue? To solve this problem, we can implement this method in the implementation class 194
Abstraction In Java Java 9 has introduced another new feature, Java 9 SE onwards we can have private methods in interfaces. Java 9 introduced private methods in interfaces to remove the redundancy by sharing the common code of multiple default methods through private methods. 195
Abstraction In Java Multiple default methods with duplicate code (java8) interface MyInterfaceInJava8 { default void method1() { System.out.println("Starting method"); System.out.println("Doing someting"); System.out.println("This is method1"); } default void method2() { System.out.println("Starting method"); System.out.println("Doing someting"); System.out.println("This is method2"); } } 196
Abstraction In Java Default methods sharing common code using private methods interface MyInterfaceInJava9 { default void method1() { //calling private method printLines(); System.out.println("This is method1"); } default void method2() { //calling private method printLines(); System.out.println("This is method2"); } private void printLines() { System.out.println("Starting method"); System.out.println("Doing someting"); } } 197
Abstraction In Java Java 9 also allows us to have private static methods in interfaces. Since java 8 we can have static methods in interfaces along with default methods. We can not share the common code of static methods using the non-static private method, we must have to use the private static method to do that. 198
Abstraction In Java interface MyInterfaceInJava9 { static void method1() { printLines(); //calling private method System.out.println("This is method1"); } static void method2() { printLines(); //calling private method System.out.println("This is method2"); } //this must be static else we will get compilation error private static void printLines() { System.out.println("Starting method"); System.out.println("Doing someting"); } default void mymethods() { method1(); method2(); } } 199
Method Overriding 1) Declaring a method in sub class which is already present in parent class is known as method overriding. 2) Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. 3) In this case the method in parent class is called overridden method and the method in child class is called overriding method. 4) The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code. 200
Method Overriding Example on method overriding class Human{ public void eat(){//Overridden method System.out.println("Human is eating"); } } class Boy extends Human{ public void eat(){//Overriding method System.out.println("Boy is eating"); } } 201
Method Overriding Rules of method overriding in Java Argument list: The argument list of overriding method (method of child class) must match the Overridden method(the method of parent class). The data types of the arguments and their sequence should exactly match. 202
Method Overriding Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the access level of parent class method is public then the overriding method (child class method ) cannot have private, protected and default access level , because all of these three access level are more restrictive than public. class MyBaseClass{ public void disp(){ System.out.println("Parent class method"); }} class MyChildClass extends MyBaseClass{ protected void disp(){//C.E System.out.println("Child class method"); }} 203
Method Overriding private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class. 204
Association In Java
Association In Java 1) Association is relation between two separate classes which establishes through their Objects. 2) Association can be one-to-one, one-to-many, many- to-one, many-to-many. 3) In Object-Oriented programming, an object communicates to other object to use functionality and services provided by that object. 4) Composition and Aggregation are the two forms of association. 206
Association In Java Aggregation or HAS-A relationship between two classes. When class A has a reference to the object of another class B, class A is said to be in a HAS-A relationship with class B. Through this reference of class B in it, class A can call and use the needed features of class B, without copying all the unnecessary code of class B in it. Let's take an example class Student{ String name; Address ad; } Here in the above code, you can say that Student has-a Address. 207
Association In Java Composition or IS-A relationship between two classes An IS-A signifies a relationship between the two classes that are connected to each other through inheritance. The basis of an IS-A relationship is - a)When a class extends another concrete(non-abstract) class. b)When a class extends an abstract class. c)When a class implements an interface. 208
String Handling In Java
String Handling In Java Introduction 1)Basically, string is a sequence of characters but it’s not a primitive type. 2)In Java, CharSequence Interface is used for representing a sequence of characters. 3)CharSequence interface is implemented by String, StringBuffer and StringBuilder classes. These three classes can be used for creating strings in java. 4)When we create a string in java, it actually creates an object of above three classes 210
String Handling In Java 211
String Handling In Java Creation of strings 1) Using string literal While creating String object using string literal, new operator is not used. String objects can be created using string literal as shown below: Example String str1 = “James”; 212
String Handlin In Java 213
String Handlin In Java What is String Constant Pool? The String Constant Pool (SCP) is a place where objects with string literals are stored. It is a part of the heap memory area. 214
String Handlin In Java 215
String Handling In Java 216 When we create a String using double quotes, JVM looks in the String pool(refers to collection of Strings which are stored in heap memory) to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
String Handling In Java 217 In the above image, two Strings are created using literal i.e “Apple” and “Mango”. Now, when third String is created with the value “Apple”, instead of creating a new object, the already present object reference is returned.
String Handling In Java 2) Using new keyword When String object is created using the new keyword, two same string objects are created. One in heap area (outside SCP) & another inside String Constant Pool (SCP). Example String str1 = new String(“James”); 218
String Handling In Java Difference between String literal and New String object When you use new String( "Hello" ), it explicitly creates a new and referentially distinct instance of a String object. It is an individual instance of the java.lang.String class. 219
String Handling In Java String s=“Harry"; may reuse an instance from the string constant pool if one is available (String Pool is a pool of Strings stored in Java heap memory ) otherwise create a new instance 220
String Handling In Java Strings Are Immutable Objects The objects in which you cannot change anything once the object is created are known as Immutable objects. Once a String object is created, it can never be changed so it is an immutable object but its reference variable is not. 221
String Handling In Java String samplestring="Machine Learning"; samplestring.concat("Masters"); System.out.println(samplestring); Variable samplestring, which stores the string “Machine Learning“. Now, if you concatenate this string with another string “Masters“, then the object created for “Machine Learning” will not change. Instead, a new object will be created for “Machine Learning Masters“. 222
String Handling In Java String Class Methods public char charAt(int index) Returns the character at the specified index. Specified index value should be between '0' to 'length() -1' both inclusive. It throws IndexOutOfBoundsException if index is invalid/ out of range. String name = "James Smith"; char ch1 = name.charAt(3) char ch2 = name.charAt(6); char ch3 = name.charAt(9); 223
String Handlin In Java 224
String Handling In Java public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) This method is used to copy set of characters of the invoking string into the specified character array. Parameters srcBegin − index of the first character in the string to copy. srcEnd − index after the last character in the string to copy. dst − the destination array. dstBegin − the start offset in the destination array. String s = "Its Beyond Simple"; int start = 4; int end = 10; char storage[] = new char[end-start]; s.getChars(start,end,storage,0); System.out.println(storage); 225
String Handlin In Java 226
String Handling In Java public byte[] getBytes() This method encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. String Str1 = new String("Welcome to NareshIt"); byte[]b=Str1.getBytes();//byte array having all charactes with ascii values 227
String Handling In Java public char[] toCharArray() This method converts this string to a new character array. It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string. String str = new String("Welcome to Nacre"); char[]ch=str.toCharArray();//array contains the all characters of the string 228
String Handling In Java boolean equals(Object anObject) Used to compare two strings. It returns true if both string represents same sequence of characters else false. String s1="hello"; String s2="welcome"; s1.equals(s2);// returns false s1.equals("hello");// returns true. 229
String Handling In Java boolean equalsIgnoreCase(String anotherString) Used to compare two strings, ignoring the case(upper or lower case). It returns true if both the string are of same length and represents same sequence of character ignoring the case else returns false. String s1="hello"; s1.equalsIgnoreCase("Hello");// returns true 230
String Handling In Java regionMatches() method This method tests if the two Strings are equal. Using this method we can compare the substring of input String with the substring of specified String. public boolean regionMatches(int toffset, String other, int ooffset, int len) Case sensitive test. public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) It has option to consider or ignore the case. 231
String Handling In Java String str1 = new String("Hello, How are you"); String str2 = new String("How"); String str3 = new String("HOW"); System.out.println(str1.regionMatches(7, str2, 0, 3)); System.out.println(str1.regionMatches(7, str3, 0, 3)); System.out.println(str1.regionMatches(true, 7, str3, 0, 3)); 232
String Handling In Java boolean startsWith(String prefix) checks if a string starts with the string represented by prefix. String s1=“refresh java”; s1.startsWith("refresh");// returns true. s1.startsWith("Refresh");// returns false. 233
String Handling In Java public boolean endsWith(String suffix) This method checks whether the String ends with a specified suffix. This method returns a boolean value true or false. If the specified suffix is found at the end of the string then it returns true else it returns false. String str1 = new String("This is a test String"); boolean var1 = str1.endsWith("String"); System.out.println("str1 ends with String: "+ var1); 234
String Handling In Java int compareTo(String str) The Java String compareTo() method is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative. String str1 = "String method tutorial"; String str2 = "compareTo method example"; int var1 = str1.compareTo( str2 ); System.out.println("str1 & str2 comparison: "+var1); 235
String Handling In Java substring() method This method is used to get the substring of a given string based on the passed indexes. There are two variants of this method. 1. When we pass only the starting index: public String substring(int beginIndex) Returns the substring starting from the specified index i.e beginIndex and extends to the character present at the end of the string. For example – "Hello".substring(1) would return "ello". 2. When we pass both the indexes, starting index and end index: public String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1. Thus the length of the substring is endIndex-beginIndex. In other words you can say that beginIndex is inclusive and endIndex is exclusive while getting the substring. For example – "Chaitanya".substring(2,5) would return "ait". 236
String Handling In Java The concat() method public String concat(String str) This method concatenates the string str at the end of the current string. For example – s1.concat("Hello"); would concatenate the String “Hello” at the end of the String s1. This method can be called multiple times in a single statement like this String s1="Nacre"; s1= s1.concat("Software").concat("Service").concat("Pvt.Ltd"); 237
String Handling In Java replace() method String replace(char oldChar, char newChar) It replaces all the occurrences of a oldChar character with newChar character. For example, "pog pance".replace('p', 'd') would return dog dance. 238
String Handling In Java replaceFirst() method String replaceFirst(String regex, String replacement) It replaces the first substring that fits the specified regular expression with the replacement String. PatternSyntaxException if the specified regular expression(regex) is not valid. String str = new String("facebook.com"); System.out.println(str.replaceFirst("com", "net")); Result is facebook.net 239
String Handling In Java replaceAll() method String replaceAll(String regex, String replacement) It replaces all the substrings that fits the given regular expression with the replacement String. String str = new String("My .com site is facebook.com"); System.out.println(str.replaceAll("com", "net")); Output is My.net site is facebook.net 240
String Handling In Java indexOf()method This method is used to find the index of a specified character or a substring in a given String. There are 4 variations of this method in String class 1)int indexOf(int ch) It returns the index of the first occurrence of character ch in a given String. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Index of J :: "+s.indexOf('J')); 2)int indexOf(int ch, int fromIndex) It returns the index of first occurrence of character ch in the given string after the specified index “fromIndex”. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Index of J from 8th index :: "+s.indexOf('J',8)); 241
String Handlin In Java 242
String Handling In Java 3)int indexOf(String str) Returns the index of string str in a particular String. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Index of JAVA :: "+s.indexOf("JAVA")); 4)int indexOf(String str, int fromIndex) Returns the index of string str in the given string after the specified index “fromIndex”. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Index of LIKE from 4th index :: "+s.indexOf("LIKE",4)); Note All the above variations returns -1 if the specified char/substring is not found in the particular String. 243
String Handling In Java 244
String Handling In Java lastIndexOf()method This method is used to find out the index of last occurrence of a character or a substring in a given String. To find out the last occurrence of the specified character or a string, this method starts the search from the end of string and proceeds backwards from there. If the fromIndex is specified during the method call, then the backward search begins from the specified index fromIndex 245
String Handling In Java 1)int lastIndexOf(int ch) It returns the last occurrence of character ch in the given String. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Last Index of J :: "+s.lastIndexOf('J')); 2)int lastIndexOf(int ch, int fromIndex) It returns the last occurrence of ch, it starts looking backwards from the specified index “fromIndex”. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Last Index of J from 16th index :: "+s.lastIndexOf('J',16)); 3)int lastIndexOf(String str) Returns the last occurrence of substring str in a String. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Last Index of LIKE :: "+s.lastIndexOf("LIKE")) 4)int lastIndexOf(String str, int fromIndex) Returns the last occurrence of str, starts searching backward from the specified index “fromIndex”. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Last Index of LIKE from 9th index :: "+s.lastIndexOf("LIKE",9)); 246
String Handlin In Java 247
String Handling In Java contains() method This method checks whether a particular sequence of characters is part of a given string or not. This method returns true if a specified sequence of characters is present in a given string, otherwise it returns false. Syntax of contains() method public boolean contains(CharSequence str) If the CharSequence is null then this method throws NullPointerException. 248
String Handling In Java intern() method 1)It is used for getting the string from the memory if it is already present. 2)This method ensures that all the same strings share the same memory. 3)This method searches the memory pool for the mentioned String, if the string is found then it returns the reference of it, else it allocates a new memory space for the string and assign a reference to it. 4)For example, creating a string “hello” 10 times using intern() method would ensure that there will be only one instance of “Hello” in the memory and all the 10 references point to the same instance. 249
String Handling In Java //String object in heap String str1 = new String("hello world"); //String literal in pool String str2 = "hello world"; //String literal in pool String str3 = "hello world"; //String object interned to literal //It will refer to existing string literal String str4 = str1.intern(); 250
String Handling In Java isEmpty()method This method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. In other words you can say that this method returns true if the length of the string is 0. public boolean isEmpty() 251
String Handling In Java join() method In Java 8 we have a new Method join() in the Java String class. Java String join() method concatenates the given Strings and returns the concatenated String. public static String join(CharSequence delimiter, CharSequence... elements) The first argument of this method specifies the delimiter that is used to join multiple strings. String message = String.join("-", "This", "is", "a", "String"); Output is: "This-is-a-String" 252
String Handling In Java split() method This method used for splitting a String into its substrings based on the given delimiter or regular expression. We have two variants of split() method in String class. 1. String[] split(String regex): It returns an array of strings after splitting an input String based on the delimiting regular expression. 2. String[] split(String regex, int limit): This Java String split method is used when we want the substrings to be limited. The only difference between this method and above method is that it limits the number of strings returned after split up. For e.g. split("anydelimiter", 3) would return the array of only 3 strings even if the delimiter is present in the string more than 3 times. 253
String Handling In Java String str = new String("28/12/2013"); String array1[]= str.split("/"); for (String temp: array1){ System.out.println(temp); } String array2[]= str.split("/", 2); for (String temp: array2){ System.out.println(temp); } 254
String Handling In Java Difference between zero and negative limit in java string split method Limit zero excludes trailing empty strings, where as negative limit includes trailing strings String s="bbaaccaa"; String arr1[]= s.split("a", -1); String arr2[]= s.split("a", 0); 255
String Handling In Java Java String split with multiple delimiters (special characters) String s = " ,ab;gh,bc;pq#kk$bb"; String[] str = s.split("[,;#$]"); Word as a regular expression in Java String split method String str = "helloxyzhixyzbye"; String[] arr = str.split("xyz"); Splitting string based on whitespace String str = "My name is Ram"; String[] arr = str.split(" "); for (String s : arr) System.out.println(s); 256
String Handling In Java format() method This method is used for formatting the String. There are so many things you can do with this method, for example you can concatenate the strings using this method and at the same time, you can format the output of concatenated string. public static String format(Locale l,String format, Object... args) Returns a formatted string using the specified locale, format string, and arguments. public static String format(String format, Object... args) Returns a formatted string using the specified format string and arguments. 257
String Handling In Java Java String Format Specifiers %c – Character %d – Integer %s – String %o – Octal %x – Hexadecimal %f – Floating number %h – hash code of a value 258
String Handling In Java String str = "just a string"; //concatenating string using format String formattedString = String.format("My String is %s", str); // %.6f is for having 6 digits in the fractional part String formattedString2 = String.format("My String is %.6f",12.121); 259
String Handling In Java We can specify the argument positions using %1$, %2$,..format specifiers. Here %1$ represents first argument, %2$ second argument and so on. String str1 = "cool string"; String str2 = "88"; String fstr = String.format("My String is: %1$s, %1$s and %2$s", str1, str2); System.out.println(fstr); Result is: My String is: cool string, cool string and 88 260
String Handling In Java Left padding an integer number with 0's and converting it into a String using Java String format() method. int str = 88; String formattedString = String.format("%05d", str); System.out.println(formattedString);// 00088 261
String Handling In Java Displaying String, int, hexadecimal, float, char, octal value using format() method String str1 = String.format("%d", 15); // Integer value String str2 = String.format("%s", "BeginnersBook.com"); // String String str3 = String.format("%f", 16.10); // Float value String str4 = String.format("%x", 189); // Hexadecimal value String str5 = String.format("%c", 'P'); // Char value String str6 = String.format("%o", 189); // Octal value 262
String Handling In Java StringBuffer Class 1)As we know that String objects are immutable, so if we do a lot of modifications to String objects, we may end up with a memory leak. To overcome this we use StringBuffer class. 2)Java StringBuffer class is used to create mutable (modifiable) string object. 3)StringBuffer class represents growable and writable character sequence. It is also thread-safe i.e. multiple threads cannot access it simultaneously. 4)Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger. 263
String Handling In Java Constructors of StringBuffer class 1)StringBuffer ( ) : Creates an empty string buffer with the initial capacity of 16. 2)StringBuffer ( int capacity ) : Creates an empty string buffer with the specified capacity as length. 3)StringBuffer ( String str ) : Creates a string buffer initialized to the contents of the specified string. 4)StringBuffer ( charSequence[] ch ) : Creates a string buffer that contains the same characters as the specified CharSequence. 264
String Handling In Java Important methods of StringBuffer class append() method The append() method concatenates the given argument(string representation) to the end of the invoking StringBuffer object. StringBuffer class has several overloaded append() method. StringBuffer append(String str) StringBuffer append(int n) StringBuffer append(Object obj) StringBuffer strBuffer = new StringBuffer("Core"); strBuffer.append("JavaGuru"); System.out.println(strBuffer); strBuffer.append(101); System.out.println(strBuffer); 265
String Handling In Java insert() method The insert() method inserts the given argument(string representation) into the invoking StringBuffer object at the given position. StringBuffer strBuffer=new StringBuffer("Core"); strBuffer.insert(1,"Java"); System.out.println(strBuffer); 266
String Handling In Java replace() method The replace() method replaces the string from specified start index to the end index. StringBuffer strBuffer=new StringBuffer("Core"); strBuffer.replace( 2, 4, "Java"); System.out.println(strBuffer); 267
String Handling In Java reverse() method This method reverses the characters within a StringBuffer object. StringBuffer strBuffer=new StringBuffer("Core"); strBuffer.reverse(); System.out.println(strBuffer); 268
String Handling In Java delete() method The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex. StringBuffer strBuffer=new StringBuffer("Core"); strBuffer.delete( 2, 4); System.out.println(strBuffer); 269
String Handling In Java capacity() method The capacity() method returns the current capacity of StringBuffer object. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur. StringBuffer strBuffer=new StringBuffer(); System.out.println(strBuffer.capacity()); strBuffer.append("1234"); System.out.println(strBuffer.capacity()); strBuffer.append("123456789112"); System.out.println(strBuffer.capacity()); strBuffer.append("1"); System.out.println(strBuffer.capacity()); //(oldcapacity*2)+2 270
String Handling In Java 271
String Handling In Java StringBuilder Class 1)StringBuilder objects are like String objects, except that they can be modified. Hence Java StringBuilder class is also used to create mutable (modifiable) string object. 2)StringBuilder is same as StringBuffer except for one important difference. StringBuilder is not synchronized, which means it is not thread safe. 3)This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread. 4)Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used. 272
String Handling In Java Constructors of StringBuilder class StringBuilder ( ) : Constructs a string builder with no characters in it and an initial capacity of 16 characters. StringBuilder ( int capacity ) : Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. StringBuilder ( String str ) : Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is 16 plus the length of the string argument. 273
String Handling In Java 274
275
Exception Handling In Java
Exception Handling In Java What is an Error? Errors are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Some Errors in Java are VirtualMachineError, OutOfMemoryError, etc. Consider a situation, when a program attempts to allocate memory from the JVM but there is not enough space to satisfy the user request. Or, when a program tries to load a class file by calling Class.forName() method and the class file is corrupt. Such exceptions are known as an error. 277
Exception Handling In Java What is an Exception? An Exception is an unexpected event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. Some common examples of Exceptions in Java are 1)Divide by zero errors 2)Trying to access the array elements with an invalid index 3)Invalid input data by the user 278
Exception Handling In Java Difference between error and exception 279 Error Exception 1. Impossible to recover from an error 1. Possible to recover from exceptions 2. Errors are of type ‘unchecked’ 2. Exceptions can be either ‘checked’ or ‘unchecked’ 3. Occur at runtime 3. Can occur at compile time or run time 4. Caused by the application running environment 4. Caused by the application itself
Exception Handling In Java What is an Exception Handling? What happen when Exception is raised? To design the program in such a way that even if there is an exception, all operations are performed then only the program should be terminated is called exception handling Whenever an exception occurs while executing a statement, creates an exception object(contains a line number where the exception occurred, type of exception ) and then the normal flow of the program halts and JRE tries to find someone that can handle the raised exception. Exception Handler is the block of code that can process the exception object. 280
Exception Handling In Java 281
Exception Handling In Java Exception Hierarchy In Java all exceptions are represented as an object of classes .All these classes are subclass of Exception. Throwable is the superclass has two subclasses Exception and Error. The Exception class, and its subclasses, is used to represent exceptional situations in a Java program that may be handled appropriately. The Error class and its subclasses, represent abnormal conditions that are caused by the application running environment. 282
Exception Handling In Java 283
Exception Handling In Java Types of Exceptions There are two types of exceptions in Java: 1)Checked exceptions 2)Unchecked exceptions Checked Exceptions A checked exception is a compile-time exception, that is, a Java compiler checks or notifies during the compilation-time. The programmer cannot simply ignore these exceptions and should take care to handle these exceptions. If the programmer does not write the code to handle them then there will be a compilation error. A checked exception extends the Exception class. Some checked Exceptions are SQLException, IOException, ClassNotFoundException, InvocationTargetException, etc. 284
Exception Handling In Java Unchecked Exceptions An exception that occurs during the execution of a program is called an unchecked or a runtime exception. So the compiler does not check whether the programmer has written the code to handle them or not but it is the responsibility of the programmer to handle the unchecked exceptions and provide a safe exit. For example, if a program attempts to divide a number by zero. Or, when there is an illegal arithmetic operation, this impossible event generates a runtime exception. Some unchecked exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, InputMismatchException, IllegalStateException, etc. 285
Exception Handling In Java In Java, exception handling is done using five keywords, 1)try 2)catch 3)throw 4)throws 5)finally Exception handling is done by transferring the execution of a program to an appropriate exception handler when exception occurs. 286
Exception Handling In Java try block 1)The try is used to define a block of code in which exceptions may occur, it must be used within the method. 2)Java try block must be followed by either catch or finally block. No intermediate statements are allowed between try and catch block or between try and finally 3)If any exception occurs in try block then CPU control comes out to the try block and executes appropriate catch block. 4)After executing appropriate catch block, CPU control never goes to try block to execute the rest of the statements. 287
Exception Handling In Java try{ } //invalid try{ } int x; catch(Exception e){ e.printStackTrace(); } //invalid try{ } int y; finally{ } //invalid try{ } catch(Exception e){ e.printStackTrace(); } //valid try{ } finally{ } //valid 288
Exception Handling In Java catch block 1)If an exception occurs within the try block, it is thrown. The catch block code catches this exception and handle it in some rational manner 2)It must be used after the try block only, you can use multiple catch block with a single try. 3)Catch block will execute exception occurs in try block. 4)You can write multiple catch blocks for handling multiple exceptions to make your application strong. 5)At a time only one catch block will execute out of multiple catch blocks. 6)In catch block you declare an object of Exception/ sub class of an Exception and it will be internally referenced by JVM. 289
Exception Handling In Java 290
Exception Handling In Java finally block 1)Java finally block is a block that is used to execute important code such as closing connection, stream etc. 2)In normal case when there is no exception in try block then the finally block is executed after try block. However if an exception occurs then the catch block is executed before finally block. 3)The statements present in the finally block execute even if the try block contains control transfer statements like return, break or continue. 4)If an exception is thrown, finally runs. If an exception is not thrown, finally runs. 5)If the exception is caught, finally runs.If the exception is not caught, finally runs 291
Exception Handling In Java 292
Exception Handling In Java 293
Exception Handling In Java Note 1)It is illegal to use a try clause without either a catch clause or a finally clause. 2) Any catch clauses must immediately follow the try block. Any finally clause must immediately follow the last catch clause (or it must immediately follow the try block if there is no catch). 3) It is legal to omit either the catch clause or the finally clause, but not both. 294
Exception Handling In Java try-with resources Generally, when we use any resources like streams, connections, etc. we have to close them explicitly using finally block. In the following program, we are reading data from a file using FileReader and we are closing it using finally block. try-with-resources, also referred as automatic resource management, is a new exception handling mechanism that was introduced in Java 7, which automatically closes the resources used within the try catch block 295
Exception Handling In Java try(FileReader fr = new FileReader("file path")) { // use the resource } catch () { // body of catch } } 296
Exception Handling In Java try with out resource management FileReader fr = null; try { File file = new File("file.txt"); fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); }finally { try { fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } 297
Exception Handling In Java try with resource management try(FileReader fr = new FileReader("E://file.txt")) { char [] a = new char[50]; fr.read(a); // reads the contentto the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); } 298
Exception Handling In Java Multiple catch blocks 1) More than one exception could be raised by a single piece of code, to handle such a situation, two or more catch clauses are specified, each catching a different type of exception. 2) Exception subclasses if any must come before any of their super classes. Otherwise, the subclass would never be reached 299
Exception Handling In Java try { int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e){ System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } catch(Exception e) { System.out.println(e); } 300
Exception Handling In Java Note While using multiple catch statements, it is important to remember that sub classes of class Exception inside catch must come before any of their super classes otherwise it will lead to compile time error. This is because in Java, if any code is unreachable, then it gives compile time error. 301
Exception Handling In Java try { int arr[]={1,2}; arr[2]=3/0; } catch(Exception e) { //This block handles all Exception System.out.println("Generic exception"); } catch(ArrayIndexOutOfBoundsException e) { //This block is unreachable System.out.println("array index out of bound exception"); } 302
Exception Handling In Java Before Java 7, we had to write multiple exception handling codes for different types of exceptions even if there was code redundancy. try { int array[] = new int[10]; array[10] = 30 / 0; } catch (ArithmeticException e) { System.out.println(e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } 303
Exception Handling In Java In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe |. Its syntax is: try { // code } catch (ExceptionType1 | Exceptiontype2 ex) { // catch block } Example try { int array[] = new int[10]; array[10] = 30 / 0; } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } 304
Exception Handling In Java If the base exception class has already been specified in the catch block, do not use child exception classes in the same catch block. Otherwise, we will get a compilation error. Example try { int array[] = new int[10]; array[10] = 30 / 0; } catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } 305
Exception Handling In Java throws clause We have a method myMethod() that has statements may generate either ArithmeticException or NullPointerException, to handle that use try-catch as shown below: public void myMethod(){ try { // Statements that might throw an exception } catch (ArithmeticException e) { // Exception handling statements } catch (NullPointerException e) { // Exception handling statements } suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable. 306
Exception Handling In Java Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword. Syntax type method_name(parameter_list) throws exception_list { // definition of method } 307
Exception Handling In Java throw clause 1)It is used for throw an exception explicitly and catch it. 2)It is used in software testing to test whether a program is handling all the exceptions as claimed by the programmer 3)throw clause can be used to throw our own exceptions 308
Exception Handling In Java Explicitly handling the exception static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } 309
Exception Handling In Java User defined exceptions/Custom exceptions Rules to design user defined Exception 1)Create a package with valid user defined name. 2)Create any user defined class. 3)Make that user defined class as derived class of Exception or RuntimeException class. 4)Declare parametrized constructor with string variable. 5)call super class constructor by passing string variable within the derived class constructor. 6)Save the program with public class name.java 310
Exception Handling In Java 311
Exception Handling In Java Rethrowing an exception There might be situations in your program where you want to both catch an exception in your code and also want its caller be notified about the exception. This is possible by rethrowing the exception using throw statement. 312
Exception Handling In Java Calling method Caller method pubic void divide() { int x,y,z; try { x = 6 ; y = 0 ; z = x/y ; System.out.println(x + "/"+ y +" = " + z); } catch(ArithmeticException e) { System.out.println("Exception Caught in Divide()"); System.out.println("Cannot Divide by Zero in Integer Division"); throw e; // Rethrows an exception } } public static void main(String[] args) { System.out.println("Start of main()"); try { divide(); } catch(ArithmeticException e) { System.out.println("Rethrown Exception Caught in Main()"); System.out.println(e); } } 313
Exception Handling In Java Nested try catch block in Java When a try catch block is present in another try block then it is called the nested try catch block. Nested try blocks are useful when different statements of try block throw different types of exceptions. If the exception thrown by the inner try block can not be caught by it’s catch block, then this exception is propagated to outer try blocks. Any one of the outer catch block should handle this exception otherwise program will terminate abruptly. 314
Exception Handling In Java try { //Outer try block //Some Statements try { //Inner try block //Some Statements } catch (Exception ex) { //Inner catch block } } catch(Exception ex) { //Outer catch block } 315
Exception Handling In Java String[] s = {"abc", "123", null, "xyz"}; //String array containing one null object for (int i = 0; i < s.length; i++){ try { //Outer try block int a = s[i].length(); //may throw NullPointerException try { //Inner try block a = Integer.parseInt(s[i]); //may throw NumberFormatException } catch (NumberFormatException ex){ //Inner catch block System.out.println("NumberFormatException will be caught here"); } } catch(NullPointerException ex){ //Outer catch block System.out.println("NullPointerException will be caught here"); } 316
Exception Handling In Java Exception Propagation Considering a scenario, in which your program starts its execution at the main() method, main() calls method1(), method1() calls method2(), method2() calls method3(), now the call stack should look like the figure below-: 317
Exception Handling In Java The currently executing method is at the top of the call stack, which in this example is method3(). Let's say while executing method3(), an exception is raised/thrown. Now this exception is thrown down to the next method in the call stack, i.e. method2(), which in turn throws the exception down to next method in the call stack, i.e. method1(). The process continues until the exception is thrown to the method at the bottom of the call stack, i.e. main() method. This process is called exception propagation 318
Exception Handling In Java class Exp{ public static void main(String... ar){ Exp ob = new Exp(); ob.method1(); } public void method1(){ method2(); } public void method2(){ method3(); } public void method3(){ System.out.println(100/0); //ArithmeticException is raised/thrown by the program. System.out.println("Hello"); //This statement will not be executed. } } 319
Problem Statements
Student Party When students get together for a party, they like to have beers. A student party is successful when the number of beers is between 40 and 60 inclusive. If it is the weekend there is no upper bound on the number of beers. Return true if the party with the given values is successful, or false otherwise. Print ‘Party Is Successful’ when return true otherwise print ‘Party Is Failure’. public Boolean party(int beers, Boolean isWeekend) { } 321
Exception Handling In Java 322
323
324
Multithreading In Java
Multithreading In Java Process Vs Thread An executing program is called a process. Each process can have a single thread or multiple threads. So that the thread is the smallest unit of a process that can run concurrently with the other parts (other threads) of the same process. 326
Multithreading In Java Process Thread An executing program is called a process. A thread is a small part of a process. Every process has its separate address space. All the threads of a process share the same address space of a process. Process-based multitasking allows a computer to run two or more than two programs concurrently. Thread-based multitasking allows a single program to run two or more threads concurrently. Communication between two processes is expensive and limited. Communication between two threads is less expensive as compared to process. Context switching from one process to another process is expensive. Context switching from one thread to another thread is less expensive as compared to process. A process has its own address space, global variables, signal handlers, open files, child processes, accounting information. A thread has its own register, state, stack, program counter. 327
Multithreading In Java Multitasking Multitasking is when a single CPU performs several tasks at the same time. To perform multitasking, the CPU switches among theses tasks very frequently so that user can interact with each program simultaneously. 328
Multithreading In Java Multithreading A process can have multiple threads simultaneously, and the CPU switches among these threads so frequently making an impression on the user that all threads are running simultaneously and this is called multithreading 329
Multithreading In Java Multitasking Multithreading In multitasking, the system allows executing multiple programs and tasks at the same time In multithreading, the system executes multiple threads of the same or different processes at the same time. In multitasking, CPU has to switch between multiple programs so that it appears that multiple programs are running simultaneously. In multithreading CPU has to switch between multiple threads to make it appear that all threads are running simultaneously. Multitasking allocates separate memory and resources for each process/program In multithreading threads belonging to the same process shares the same memory and resources as that of the process.330
Multithreading In Java Achieve multithreading in java In java language multithreading can be achieve in two different ways. 1)Using Thread class 2)Using Runnable interface 331
Multithreading In Java Using Thread Class 1)Create any user defined class and make that one as a derived class of Thread class. class MyThread extends Thread{ } 2)Override run() method of Thread class (It contains the logic of perform any operation) 3)Create an object for user-defined thread class and attached that object to predefined thread class object. MyThread obj=new MyThread(); Thread t=new Thread(obj); 4)Call start() method of thread class to execute the thread t.start(); 332
Multithreading In Java 333
Multithreading In Java Using Runnable Interface 1)Define the class that implements the Runnable interface and implement the run () method of the Runnable interface in the class. 2)Create an instance of the defined class. 3)Create an instance of the Thread class using the Thread (Runnable target) constructor. 4)Start the thread by invoking the start () method on your Thread object. 334
Multithreading In Java Why don’t we call run() method directly, why call start() method? 1) When you directly call the run() method then the code inside run() method is executed in the same thread which calls the run method. JVM will not create a new thread until you call the start method. 2) On the other hand, when you call the Thread.start() method, then the code inside run() method will be executed on a new thread, which is actually created by the start() method. 3) You can call the run method multiple time, JVM will not throw any error but when you cannot call the start() method on same thread instance. 4) The first time, t.start() will create a new thread but the second time it will throw java.lang.IllegalStateException, because the thread is already started and you cannot restart it again, you can only pause a thread in Java. 335
Multithreading In Java Directly calling the run() method 336 public void run(){ for(int i=1;i<=3;i++){ try{ Thread.sleep(1000); } catch(InterruptedException ie){ ie.printStackTrace(); } System.out.println(i); } } public static void main(String args[]){ Thread th1 = new Thread(new RunMethodExample(), "th1"); Thread th2 = new Thread(new RunMethodExample(), "th2"); th1.run(); th2.run(); }
Multithreading In Java Execute the thread by using start()method 337 public void run(){ for(int i=1;i<=3;i++){ try{ Thread.sleep(1000); } catch(InterruptedException ie){ ie.printStackTrace(); } System.out.println(i); } public static void main(String args[]){ Thread th1 = new Thread(new RunMethodExample(), "th1"); Thread th2 = new Thread(new RunMethodExample(), "th2"); th1.start(); th2.start(); }
Multithreading In Java Difference between Thread and Runnable 338 Thread Class Runnable Interface Each thread creates a unique object and gets associated with it so more memory required. Multiple threads share the same objects. So less memory is used. In Java, multiple inheritance not allowed hence, after a class extends Thread class, it can not extend any other class. If a class define thread implementing the Runnable interface it has a chance of extending one class. A user must extend thread class only if it wants to override the other methods in Thread class. If you only want to specialize run method then implementing Runnable is a better option. Extending Thread class introduces tight coupling as the class contains code of Thread class and also the job assigned to the thread Implementing Runnable interface introduces loose coupling as the code of Thread is separate form the job of Threads.
Multithreading In Java Thread Life Cycle The various states of java thread 1) New 2) Runnable 3) Running 4) Waiting 5) Timed Waiting 6) Blocked 7) Terminated 339
Multithreading In Java 340
Multithreading In Java New State 1)Whenever we create an instance of Thread, Thread gets a state called “ New ” state. 2)In this case, Thread is just created but not started, in other words we have a thread object but there is no thread execution. Thread t1 = new Thread (); 341
Multithreading In Java Runnable State 1)Whenever we start the thread it moves from “ New ” state to “ Runnable ” state. 2)In this case, thread is ready to be executed but it’s just waiting for the Thread scheduler to pick it for execution. 3)In this state, a new call stack will be created for the thread. 4)Below line takes the thread from “ New ” state to “ Runnable ” state. t.start(); 342
Multithreading In Java Running State 1) This is not the standard thread state defined by Java but its used to indicate that the thread is currently running or executing the logic. 2) Moving thread from “ Runnable ” state to “ Running ” state is entirely dependent on Thread scheduler. Thread scheduler is the one which decides whether to move the thread from “ Runnable ” state to “ Running ” state or put it on hold in “ Runnable ” state by giving chance to other Runnable threads. 3) Thread scheduler is operating system dependent most of the operating systems follow Round-robin scheduling. In this case, each thread is given a fixed amount of processor time called as “ quantum ” or “ time slice ” within which it has to execute. 4) Any thread which has got this time slice to execute its task is said to be in “ Running ” state. 5) Once time slice expires, thread will be returned to “ Runnable ” state and another thread will be assigned to the processor. 6) This process that operating system uses to determine which thread has to go from “ Runnable ” state to “ Running ” state is called “ Thread scheduling ” 343
Multithreading In Java Waiting State 1)In this case,Thread will be moved from “ Running ” state to “ Waiting ” state by calling its wait() method. 2)This can be done whenever we want currently running thread to wait for some other thread to execute and notify back to it to continue the execution. 3)Once the thread wait is notified , then the waited thread will be moved to “ Runnable ” state. 344
Multithreading In Java Timed waiting state 1)In this case, Thread will be moved from “ Running ” state to “ Waiting ” state with specified waiting time. 2)This can be done whenever we want currently running thread to wait for some specified amount of time. 3)Once the specified amount of time is completed, then the waited thread will be moved to “ Runnable ” state. 4)We can put the thread to “ Timed waiting ” by calling sleep(long millis) or wait(long millis) method 345
Multithreading In Java Blocked State 1)In this case, thread will be moved from “ Running ” state to “ Blocked ” state. 2)This can happen due to various reasons like 1) Current thread might try to read data from IO stream but there is not data to read. 2) Thread might be waiting to acquire the lock to enter synchronized block. 3)Thread will be moved from "Blocked" state to “ Runnable ” state once the data on the stream is available or lock is released by other thread. 346
Multithreading In Java Terminated State 1)Thread will be moved to Terminated state(also called Dead state) when it completes its execution successfully. 2)It can also be terminated forcefully by killing it. 347
Multithreading In Java Terminating the Thread A thread will terminate automatically when it comes out of run() method. To terminate the thread on our own the following steps can be used 1) Create a boolean type variable and initialize it to false boolean stop=false; 2) Let us assume that we want to terminate the thread when the user press<Enter>key. So, when the user press that button, make the boolean type variable as true stop=true; 3) Check this variable in run()method and when it is true, make the thread return from the run() method. public void run(){ if(stop==true)return; } 348
Multithreading In Java Single Tasking Using a Thread 1)A thread can be employed to execute one task at a time. Suppose there are 3 tasks to be executed. We can create a single thread and pass these 3 tasks one by one to the thread is called as single tasking using a thread. 2)For this purpose, we can write all these tasks separately in separate methods: task1(), task2(),task3(). 3)Then these methods should be called from run() method, one by one. 4)A thread executes only the code inside the run() method. It can never execute other methods unless they are called from run(). 349
Multithreading In Java Multi Tasking Using Threads In multi tasking, several tasks are executed at a time. For this purpose we need more than one thread. For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks. Then those tasks are simultaneously executed by two threads. This is called as multi threading 350
Multithreading In Java When we go to a movie theatre, generally a person is there at the door-checking and cutting the tickets. When we enter the hall, there is another person who shows the seats for us. Suppose there is only one person (1 thread) doing these two tasks. He has to first cut the ticket and then come along with us to show the seat. Then he goes back to the door to cut the second ticket and then again enter the hall to show the seat for second ticket. Like this, if he is does the things one by one, it takes a lot of time, and even though the show is over, there will be still a few people left outside the door waiting to enter the hall. The solution is theatre management employ two persons(2 threads) for this purpose. The first person will cut the ticket, and the second person will show the seat. When the second person is showing the seat, the first person cut the second ticket. Like this, both the persons can act simultaneously and hence there will be no wastage of time. 351
Multithreading In Java Multiple Threads Acting on Single Object • Multiple threads acting on single object means two or more threads should share the same object (same run() method). In this case we get unreliable results • For example, take the case of railway reservation system. Everyday several people want reservation of a berth for them. The procedure to reserve the berth is same for all the people. So we need same object with same run() method to be executed repeatedly for all the people • Let us think that only one berth is available in a train, and two passengers are asking that berth. In reservation counter no.1, the clerk has sent a request to the server to allot that berth to his passenger. In counter no.2, the second clerk has also sent a request to the server to allot that berth to his passenger. Let us see now to whom that berth is allotted. 352
Multithreading In Java Thread Synchronization  Whenever multiple threads are trying to use same resource than they may be chance to of getting wrong output, to overcome this problem thread synchronization can be used.  Allowing only one thread at a time to utilized the same resource out of multiple threads is known as thread synchronization or thread safe.  In java thread synchronization can be achieve in two different ways.  Synchronized block  Synchronized method 353
Multithreading In Java Synchronized block • Whenever we want to execute one or more than one statement by a single thread at a time(not allowing other thread until thread one execution is completed) than those statement should be placed in side synchronized block. 354
Multithreading In Java Synchronized method • Whenever we want to allow only one thread at a time among multiple thread for execution of a method than that should be declared as synchronized method. 355
Multithreading In Java 356
Multithreading In Java Difference between synchronized keyword and synchronized block When we use synchronized keyword with a method, it acquires a lock in the object for the whole method. It means that no other thread can use any synchronized method until the current thread, which has invoked it's synchronized method, has finished its execution. synchronized block acquires a lock in the object only between parentheses after the synchronized keyword. This means that no other thread can acquire a lock on the locked object until the synchronized block exits. But other threads can access the rest of the code of the method. Which is more preferred - Synchronized method or Synchronized block? In Java, synchronized keyword causes a performance cost. A synchronized method in Java is very slow and can degrade performance. So we must use synchronization keyword in java when it is necessary else, we should use Java synchronized block that is used for synchronizing critical section only. 357
Multithreading In Java Deadlock in threads • Deadlock is a situation of complete Lock, when no thread can complete its execution because lack of resources. In the b picture, Thread 1 is holding a resource R1, and need another resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock. 358
Multithreading In Java 359
Multithreading In Java • To book a ticket, the thread will enter the train object to verify that the ticket is available or not. When there is a ticket, it updates the available number of tickets in the train object. For this, it takes, 150 milliseconds. Then it enters the compartment object. In compartment object, it should allot the ticket for the passenger and update its status to reserved. This means the thread should go through both the train and compartment objects. • Let us think if a thread has to cancel a ticket, it will first enter compartment object, and updates the status of the ticket as available. For this it is taking 200 milliseconds. Then it enters train object and updates the available number of tickets there. So, this thread also should go through both the compartment and train objects 360
Multithreading In Java • When BookTicket thread is at train object for 150 milliseconds, the CancelTicket thread will be at compartment object for 200 milliseconds. We are using multiple threads we should synchronize them. So, the threads will lock those objects • When 150 milliseconds time is over, BookTicket thread tries to comeout of train object and wants to lock on compartment object, by entering it.At that time, it will find that the comaprtment object is already locked by another thread(CancelTicket) and hence it will wait, BookTicket thread will wait for compartment object for another 50 milliseconds. • After 200 milliseconds time is up, the CancelTicket thread which is in compartment object completes its execution and wants to enter and lock on train object. But it will find that the train object is laready under lock by BookTicket thread and hence is not available. Now, CancelTicket will wait for the train object which should be unlocked by BookTicket. • Both the threads will wait forever in this way, suspending any further execution. This situation is called ‘Thread Deadlock’. 361
Multithreading In Java Thread Priorities 1)Every thread in Java has a priority that helps the thread scheduler to determine the order in which threads scheduled. 2)The threads with higher priority will usually run before than lower priority threads. 3)By default, all the threads had the same priority. 4)However, you can explicitly set a thread's priority at any time after its creation by calling its setPriority() method. 5)This method accepts an argument of type int that defines the new priority of the thread. Its syntax is. final void setPriority(int priority) 362
Multithreading In Java 6) Priority is an integer value that must range between 1 and 10, with 10 being the highest priority, 1 being the lowest and 5 being the default. 7) If you specify a priority that is out of range, then an IllegalArgumentException exception thrown. 8) Some thread priorities are static member variables of java.lang.Thread class. 9) These include MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY representing values 1,5 and 10 respectively. 10) The priority of the main thread is Thread.NORM_PRIORITY, i.e., 5. NOTE: Generally higher priority threads can be expected to be given preference by the thread scheduler over lower priority threads. However, the implementation of thread schduling is left upto the JVM implementation. 363
Multithreading In Java 364
Multithreading In Java The Methods to Prevent a Thread from Execution We can prevent(stop) a Thread execution by using the following methods. 1)yield(); 2)join(); 3)sleep(); 365
Multithreading In Java yield() method 1)yield() method causes "to pause current executing Thread for giving the chance of remaining waiting Threads of same priority". 2)If all waiting Threads have the low priority or if there is no waiting Threads then the same Thread will be continued its execution. 3)If several waiting Threads with same priority available then we can't expect exact which Thread will get chance for execution. 4)The Thread which is yielded when it get chance once again for execution is depends on mercy of the Thread scheduler. public static native void yield() Note : Some operating systems may not provide proper support for yield() method. 366
Multithreading In Java 367
Multithreading In Java join() method If a Thread wants to wait until completing some other Thread then we should go for join() method. Example: If a Thread t1 executes t2.join() then t1 should go for waiting state until completing t2. Note Every join() method throws InterruptedException, which is checked exception hence compulsory we should handle either by try catch or by throws keyword. 368
Multithreading In Java 369
Multithreading In Java You have three threads T1, T2, and T3, How do you ensure that they finish in order T1, T2, T3 ?. You can do this by using join method, by calling T1.join() from T2 and T2.join() from T3. In this case thread, T1 will finish first, followed by T2 and T3. 370
Multithreading In Java sleep() method If a Thread don't want to perform any operation for a particular amount of time then we should go for sleep() method. public static native void sleep(long ms) throws InterruptedException public static void sleep(long ms,int ns)throws InterruptedException 371
Multithreading In Java 372
Multithreading In Java Interrupting a Thread How a Thread can interrupt another thread ? If a Thread can interrupt a sleeping or waiting Thread by using interrupt()(break off) method of Thread class. public void interrupt() Note 1) Whenever we are calling interrupt() method we may not see the effect immediately, if the target Thread is in sleeping or waiting state it will be interrupted immediately. 2) If the target Thread is not in sleeping or waiting state then interrupt call will wait until target Thread will enter into sleeping or waiting state. Once target Thread entered into sleeping or waiting state it will effect immediately. 3) In its lifetime if the target Thread never entered into sleeping or waiting state then there is no impact of interrupt call simply interrupt call will be wasted. 373
Multithreading In Java Daemon Thread Java defines two types of thread: user thread (normal thread) and daemon thread. By default, when you create a new thread it is user thread. The Java Virtual Machine (JVM) won’t terminate if there are still user threads running. But it will exit if there are only daemon threads running. Daemon threads have lower priority than normal ones, so they are used for running background services that serve user threads. An example of daemon thread in the JVM is the garbage collector thread that runs silently in the background to free unused memory. 374
Multithreading In Java Methods of Thread class that are related to Daemon threads: public void setDaemon(boolean status) This method is used for making a user thread to Daemon thread or vice versa. For example if I have a user thread t then t.setDaemon(true) would make it Daemon thread. On the other hand if I have a Daemon thread td then by calling td.setDaemon(false) would make it normal thread(user thread/non-daemon thread). public boolean isDaemon() This method is used for checking the status of a thread. It returns true if the thread is Daemon else it returns false. 375
Multithreading In Java Note setDaemon() method can only be called before starting the thread. This method would throw IllegalThreadStateException if you call this method after Thread.start() method. 376
Multithreading In Java Inter Thread Communication Polling Problem The process of testing a condition repeatedly till it becomes true is known as polling. Example Suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waits for the producer to produce. Once the producer has finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. 377
Multithreading In Java The solution for polling problem is inter-thread communication Inter-thread communication Inter-thread communication is a process in which a thread is paused running in its critical region and another thread is allowed to enter (or lock) in the same critical region to be executed. i.e. synchronized threads communicate with each other. For inter-thread communication java provides three methods they are wait(), notify() and notifyAll(). All these methods belong to object class as final so that all classes have them. They must be used within a synchronized block only. 378
Multithreading In Java • wait()-It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify(). • notify()-It wakes up one single thread that called wait() on the same object. It should be noted that calling notify() does not actually give up a lock on a resource. • notifyAll()-It wakes up all the threads that called wait() on the same object. 379
Multithreading In Java ThreadGroup in Java 1)A ThreadGroup represents a set of threads. So we can suspend, resume or interrupt group of threads by a single method call. 2)A thread group can also include the other thread group. The thread group creates a tree in which every thread group except the initial thread group has a parent. 3)A thread is allowed to access information about its own thread group, but it cannot access the information about its thread group's parent thread group or any other thread groups. 4)Java thread group is implemented by java.lang.ThreadGroup class. 380
Multithreading In Java 381
Multithreading In Java Constructors of ThreadGroup class ThreadGroup(String name) creates a thread group with given name. ThreadGroup base = new ThreadGroup("Base"); ThreadGroup(ThreadGroup parent, String name) creates a thread group with given parent group and name. ThreadGroup group1 = new ThreadGroup(base, "Group1"); 382
Multithreading In Java Important methods of ThreadGroup class activeCount():returns an estimate of the number of active threads in the thread group and its subgroups. destroy():destroys the thread group and all of its subgroups. enumerate(Thread[] list):copies into the specified array every active thread in this thread group and its subgroups. getMaxPriority():returns the maximum priority of the thread group. interrupt():interrupts all threads in the thread group. isDaemon():tests if the thread group is a daemon thread group. setMaxPriority(int priority): sets the maximum priority of the group. 383
Multithreading In Java Thread Pool 1)In terms of performance, creating a new thread is an expensive operation because it requires the operating system allocates resources need for the thread. 2)Instead of creating new threads when new tasks arrive, a thread pool keeps a number of idle threads that are ready for executing tasks as needed. After a thread completes execution of a task, it does not die. Instead it remains idle in the pool waiting to be chosen for executing new tasks. 3)You can limit a definite number of concurrent threads in the pool, which is useful to prevent overload. If all threads are busily executing tasks, new tasks are placed in a queue, waiting for a thread becomes available. 384
Multithreading In Java The Java Concurrency API supports the following types of thread pools: 1)Cached thread pool: keeps a number of alive threads and creates new ones as needed. 2)Fixed thread pool: limits the maximum number of concurrent threads. Additional tasks are waiting in a queue. 3)Single-threaded pool: keeps only one thread executing one task at a time. 4)Fork/Join pool: a special thread pool that uses the Fork/Join framework to take advantages of multiple processors to perform heavy work faster by breaking the work into smaller pieces recursively. 385
Multithreading In Java What is an Executor? An Executor is an object that is responsible for threads management and execution of Runnable tasks submitted from the client code. It decouples the details of thread creation, scheduling, etc from the task submission so you can focus on developing the task’s business logic without caring about the thread management details. That means, rather than creating a thread to execute a task like this: Thread t = new Thread(new RunnableTask()); t.start(); You submit tasks to an executor like this: Executor executor = anExecutorImplementation; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); 386
Multithreading In Java The Java Concurrency API defines the following 3 base interfaces for executors: 1)Executor: is the super type of all executors. It defines only one method execute(Runnable). 2)ExecutorService: is an Executor that allows tracking progress of value-returning tasks (Callable) via Future object, and manages the termination of threads. Its key methods include submit() and shutdown(). 3)ScheduledExecutorService: is an ExecutorService that can schedule tasks to execute after a given delay, or to execute periodically. Its key methods are schedule(), scheduleAtFixedRate() and scheduleWithFixedDelay(). 387
Multithreading In Java You can create an executor by using one of several factory methods provided by the Executors utility class. 1) newCachedThreadPool(): creates an expandable thread pool executor. New threads are created as needed, and previously constructed threads are reused when they are available. Idle threads are kept in the pool for one minute. This executor is suitable for applications that launch many short-lived concurrent tasks. 2) newFixedThreadPool(int n): creates an executor with a fixed number of threads in the pool. This executor ensures that there are no more than n concurrent threads at any time. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread becomes available. If any thread terminates due to failure during execution, it will be replaced by a new one. The threads in the pool will exist until it is explicitly shutdown. Use this executor if you and to limit the maximum number of concurrent threads. 388
Multithreading In Java 3) newSingleThreadExecutor(): creates an executor that executes a single task at a time. Submitted tasks are guaranteed to execute sequentially, and no more than one task will be active at any time. Consider using this executor if you want to queue tasks to be executed in order, one after another. 4) newScheduledThreadPool(int corePoolSize): creates an executor that can schedule tasks to execute after a given delay, or to execute periodically. Consider using this executor if you want to schedule tasks to execute concurrently. 5) newSingleThreadScheduleExecutor(): creates a single-threaded executor that can schedule tasks to execute after a given delay, or to execute periodically. Consider using this executor if you want to schedule tasks to execute sequentially. 389
Multithreading In Java 390
Multithreading In Java 391
Multithreading In Java 392
Multithreading In Java 393
394
Collection framework
Collection framework What is a collection? In terms of programming, a collection is a data structure that holds a set of objects in a specific manner. It looks like arrays but collections are more advanced and more flexible. An array simply stores a fixed number of objects, whereas a collection stores variable number of objects dynamically, i.e. you can add or remove objects as you wish. A collection also provides useful operations such as adding, removing, retrieving objects. 396
Collection framework What is Collection Framework 1)A Collection Framework in Java is a unified architecture that represents a collection of interfaces and classes. It helps in storing and processing the data efficiently. 2)Java Collections Framework provides useful and robust algorithms such as searching and sorting on collections, and the interoperability between collections and arrays. 3)The Java collections framework provides various data structures and algorithms that can be used directly. It means we do not have to write code to implement these data structures and algorithms manually. 4)The two principal root interfaces of Java collection classes are Collection interface and Map interface . 397
Collection framework Collection Framework Hierarchy 398
Collection framework Collection Interface The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. 399
Collection framework Some important methods of Collection interface 400 S.No Method Name Description 1 boolean add(Object obj) Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, when that collection does not allow duplicates. 2 boolean addAll(Collection c) Adds all the elements of c to the invoking collection. Returns true if the operation succeeds (i.e., the elements were added). Otherwise, returns false. 3 void clear( ) Removes all elements from the invoking collection. 4 boolean contains(Object obj) Returns true if obj is an element of the invoking collection. Otherwise, returns false.
Collection framework 5 boolean containsAll(Collection c) Returns true if the invoking collection contains all elements of c. Otherwise, returns false. 6 boolean equals(Object obj) Returns true if the invoking collection and obj are equal. Otherwise, returns false. 7 int hashCode( ) Returns the hash code for the invoking collection. 8 boolean isEmpty( ) Returns true if the invoking collection is empty. Otherwise, returns false. 9 Iterator iterator( ) Returns an iterator for the invoking collection. 10 boolean remove(Object obj) Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false. 11 boolean removeAll(Collection c) Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. 401
Collection framework 12 boolean retainAll(Collection c) Removes all elements from the invoking collection except those in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. 13 int size( ) . Returns the number of elements held in the invoking collection 14 Object[ ] toArray( ) Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements. 15 Object[ ] toArray(Object array[ ]) Returns an array containing only those collection elements whose type matches that of array. 402
Collection framework 403
Collection framework 404
Collection framework 405
Collection framework 406
Collection framework 407
Collection framework 408
Collection framework 409
Collection framework 410
Collection framework 411
Collection framework 412
Collection framework 413
Collection framework 414
Collection framework 415
Collection framework 416
Collection framework 417
Collection framework 418
Collection framework 419
Collection framework 420
Collection framework 421
Collection framework 422
Collection framework 423
Collection framework 424
Collection framework 425
426
427
428
JVM Architecture • First of all, the .java program is converted into a .class file consisting of byte code instructions by the Java compiler • JVM(Java Virtual Machine) is responsible for taking the .class file and converting each byte code instruction into the machine language instruction that can be executed by the processor 429
JVM Architecture 430
JVM Architecture • In JVM, there is a program called classloader sub system, which performs the following functions 1)First of all, it loads the .class file into memory 2)Then it verifies whether all byte code instructions are proper or not. If it finds any instruction suspicious, the execution is rejected immediately 3)If the byte code instructions are proper, then it allocates necessary memory to execute the program • This memory divided into 5 parts, called run time data areas 431
JVM Architecture Method area • It is the memory block, which stores the class code, code of the variables, and code of the methods in the Java program Heap • This is the area where objects are created. Whenever JVM loads a class, a method and a heap area are immediately created in it. 432
JVM Architecture Java Stacks • Method code stored on Method area. But while running a method, it needs some more memory to store the data and results. This memory is allocated on Java stacks. So, Java Stacks are memory areas where Java methods are executed. 433
JVM Architecture PC(Program Counter) registers • These are the registers which contain memory address of the instructions of the methods. If there are 3methods, 3 PC registers will be used to track the instructions of the methods Native method stacks • Java method are executed on Java stacks. Similarly, native methods(C/C++ functions) are executed on Native method stacks. To execute native methods, native method libraries are required. These header files are located and connected to JVM by a program, called Native method interface 434
Factory Methods
Factory Methods • Factory methods are static methods only • A factory method is a method that creates and returns an object to the class to which it belongs. • The aim of factory method is to create an object depending on the user option. Example :public static Fees getFees(String course) { } Above method takes the course from the user and creates an object either to CSE class or ECE class depending on the user option 436
Different Ways Object Creation In Java
Different Ways Object Creation In Java 1) Using new operator Employee obj=new Employee(); 2) Using factory methods NumberFormat obj=NumberFormat.getNumberInstance(); 3) Using newInstance() method Class c=Class.forName(“Employee”); Empoyee obj=(Employee)c.newInstance(); 4) By cloning an already available object Employee obj1=new Employee(); Employee obj2=(Employee)obj1.clone(); 438
Object Class In Java
Object Class 1) There is a class with the name ‘Object’ I java.lang package which is the super class of all classes in Java 2) Every class in Java is a direct or indirect sub class of the Object class 3) The Object class defines the methods to compare objects, to convert an object into String, etc. 440
Object Class Methods of Object class 441 Method Description equals() Compares the references of two objects return true when they are equal otherwise return false toString() Returns a string representation of an object getClass() It gives an object that contains the name of a class to which an object belongs hashCode() Returns hashcode number of an object notify() Sends a notification to a thread which is waiting for an object notifyAll() Sends a notification for all waiting threads for the object wait() Causes a thread to wait till a notification is received from a notify() or notifyAll() methods
Object Class equals() method 1)This method normally compares the references of two objects 2)If both the references refer to same object, then it gives true, otherwise it gives false 3)But in case of String objects and wrapper class objects it compares the contents of the objects 4)If the content are same then it returns true, otherwise false 442
Object Class hashCode() method 1)Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode() method must consistently return the same integer 2)If two objects are equal according to the equals() method, then calling the hashCode() method on each of the two objects must produce the same integer result 3)If two objects are unequal according to the equals() method, then calling the hashCode() method on each of the two objects must produce distinct integer results 443
Exception Propagation
Exception Propagation • Considering a scenario, in which your program starts its execution at the main() method, main() calls method1(), method1() calls method2(), method2() calls method3(), now the call stack should look like 445
Exception Propagation • The currently executing method is at the top of the call stack, which in this example is method3(). Let's say while executing method3(), an exception is raised/thrown. Now this exception is thrown down to the next method in the call stack, i.e. method2(), which in turn throws the exception down to next method in the call stack, i.e. method1(). The process continues until the exception is thrown to the method at the bottom of the call stack, i.e. main() method. 446
Exception Propagation • The currently executing method is at the top of the call stack, which in this example is method3(). Let's say while executing method3(), an exception is raised/thrown. • Now this exception is thrown down to the next method in the call stack, i.e. method2(), which in turn throws the exception down to next method in the call stack, i.e. method1(). • The process continues until the exception is thrown to the method at the bottom of the call stack, i.e. main() method. This is called as exception propagation Note: • Only unchecked exceptions are propagated. Checked exceptions throw compilation error. 447
Try-With-Resource
Try-With-Resource Syntax try(resource-specification(there can be more than one resource)) { //use the resource } catch() { ... } 449
Try-With-Resource • This try statement contains a parenthesis in which one or more resources is declared. • A resource is an object that is used in program and must be closed after the program is finished. • The try-with-resources statement ensures that each resource is closed at the end of the statement of the try block. You do not have to explicitly close the resources. 450
Catch multiple exceptions in Java1.7
Catch multiple exceptions • In Java 7 it was made possible to catch multiple different exceptions in the same catch block. try { // execute code that may throw 1 of the 3 exceptions below. } catch(SQLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } 452
Catch multiple exceptions try { // execute code that may throw 1 of the 3 exceptions below. } catch(SQLException | IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } 453
Rethrowing the exception
Rethrowing The Exeption • There might be situations in your program where you want to both catch an exception in your code and also want its caller be notified about the exception. • This is possible by rethrowing the exception using throw statement. 455
Thread Deadlock
Thread Deadlock • Deadlock is a situation of complete Lock, when no thread can complete its execution because lack of resources. In the above picture, Thread 1 is holding a resource R1, and need another resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock. 457
Thread Deadlock 458
Interthread Communication
Interthread Communication Polling Problem The process of testing a condition repeatedly till it becomes true is known as polling. Example Suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waits for the producer to produce. Once the producer has finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. 460
Inter-thread communication The solution for polling problem is inter-thread communication Inter-thread communication Inter-thread communication is a process in which a thread is paused running in its critical region and another thread is allowed to enter (or lock) in the same critical region to be executed. i.e. synchronized threads communicate with each other. For inter-thread communication java provides three methods they are wait(), notify() and notifyAll(). All these methods belong to object class as final so that all classes have them. They must be used within a synchronized block only. 461
Interthread Communication • wait()-It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify(). • notify()-It wakes up one single thread that called wait() on the same object. It should be noted that calling notify() does not actually give up a lock on a resource. • notifyAll()-It wakes up all the threads that called wait() on the same object. 462
Daemon thread
Daemon Thread • Daemon threads are low priority threads which are act as a service provider for user threads. Life of a daemon thread is depends upon the user threads. JVM automatically terminates daemon thread when all user threads are died. Daemon threads are used for background supporting tasks. Methods used for daemon threads: 1. public final void setDaemon(boolean on) Marks this thread as daemon thread if on is true. 2. public final boolean isDaemon() Returns true if thread is daemon. 464
Java Annotations
Java Annotations • Java annotations were added to Java from Java 5. • Java annotations are used to provide the meta data to our Java code. • Meta data is the additional information which can be used for any class, interface, method or field. • Java annotations can be used as an alternative option for XML and java marker interfaces. 466
Java Annotations Java annotations are mainly used for the following: Compiler instructions used to give certain instructions to the compiler Build-time instructions can be used by the build tools for generating source code, generating XML files, packaging the compiled code and files into a JAR file etc. Runtime instructions These annotations can be accessed using Java Reflection. 467
Java Annotations • A java annotation always starts with the symbol @ and followed by the annotation name Syntax: Example: @AnnotationName @Entity • An annotation can contain zero, one or multiple elements. We have to set values for these elements. Example: @Entity(tableName = "USERS") We can use java annotations above classes, interfaces, methods, fields and local variables. Here is an example annotation added above a class definition: 468
Java Annotations Java Annotations List: • @Deprecated • @Override • @SuppressWarnings • @Target • @Retention • @Inherited • @Documented 469
Java Annotations @Deprecated java annotation • The deprecated terms in software development is refers to classes, interfaces, functions or elements that are in the process of being replaced by newer ones. • The @Deprecated java annotation signals that the marked element is deprecated and should no longer be used. 470
Java Annotations @Override java annotation • The @Override java annotation indicates that the subclass method is overriding the parent class method. • If we are not using override annotation it may be the case someone changed the name of the overridden method in the superclass, in that case subclass method would no longer override it. 471
Java Annotations @SuppressWarningsjava annotation • The @SuppressWarnings annotation type allows Java programmers to disable compilation warnings for a certain part of a program (type, field, method, parameter, constructor, and local variable). 472
473
Object Oriented Programming
Object Oriented Programming What is object oriented programming? • Object-Oriented Programming is a programming pattern that makes use of objects and their interactions to design and implement applications • Objects are entities that serve as the basic building blocks of an object-oriented application • An object is a self-contained entity with attributes and behaviors 475
Object Oriented Programming 476
Object Oriented Programming What is an Object?  An entity which does exist, has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc.  If something does not really exist, then it is not an object e.g. our thoughts, imagination, plans, ideas etc.,  According to System existence means contains memory. So a software object represent a memory.  Software objects also have a state and a behavior. A software object's state is stored in variables and behavior is shown via methods. So an object contains variables and methods 477
Object Oriented Programming What is a Class?  It is possible that some objects may have similar properties and actions. Such objects belongs to same category called a ‘class’  It is only an logical component and not the physical entity e.g. if you had a class called “Expensive Cars” it could have objects like Mercedes, BMW, Toyota, etc.  Its properties(data) can be price or speed of these cars.  While the methods may be performed with these cars are driving, reverse, braking etc. 478
Object Oriented Programming 479
Object Oriented Programming What is an abstraction in Java? In object oriented programming abstraction is a process of providing functionality to the users by hiding its implementation details from them In other words, the user will have just the knowledge of what an entity is doing instead of its implementation 480
Object Oriented Programming Real life example of Abstraction is ATM Machine; All are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about ATM. 481
Object Oriented Programming Advantages of Abstraction 482
Object Oriented Programming How to Achieve Abstraction in Java? In Java, we can achieve Data Abstraction using Abstract class and Interface Interface allow 100% abstraction(complete abstraction). Interface allow you to abstract the implementation completely Abstract class allow 0 to 100% abstraction (partial to complete abstraction)because abstract class can contain concrete methods that have the implementation which results in a partial abstraction 483
Object Oriented Programming What is an Encapsulation? 1)We can define it as Encapsulation is the wrapping up of data and functions (methods that operate on the data) into a single unit (called class). 2)There is a prohibition for direct access to the data. Functions (that combine with the data) are the only way to access data. These functions are the member functions or methods in Java. It basically creates a shield due to which the code or data cannot be accessed outside the shield. 3)In Java class bind the data with its associated method so class is an example of encapsulation 484
Object Oriented Programming 485
Object Oriented Programming Achieving Encapsulation in Java In order to achieve encapsulation in Java, we have to 1)declare the variables of a class as private, so that they cannot be accessed directly from outside the class. 2)provide setter and getter methods that are declared as public, to view and change the values of the variables. 486
Object Oriented Programming Inheritance in Java 1)The process by which one class acquires the properties(data members) and functionalities(methods) of another class is called inheritance. 2)In the inheritance the class which is give data members and methods is known as base or super or parent class. 3)The class which is taking the data members and methods is known as sub or derived or child class 487
Object Oriented Programming 488
Object Oriented Programming Polymorphism in Java Polymorphism is the ability for a data or message to be processed in more than one form. It is a concept by which a single operation can be performed in multiple different ways. For example, a security guard outside an organization behaves differently with different people entering the organization. He acts in a different way when the Boss comes and, in another way when the employees come. When the customers enter, the guard will respond differently. So here, the behavior of the guard is in various forms, which depends on the member who is coming. 489
Object Oriented Programming 490
Object Oriented Programming We can define polymorphism in the context of Object-Oriented Programming as follows: “The virtue (good future) by which the same action can be performed by objects of different classes and each object responds in a different way depending on its class is called Polymorphism”. 491
Object Oriented Programming 492
Object Oriented Programming 493
Object Oriented Programming 494
Object Oriented Programming 495
Object Oriented Programming 496
Wrapper Classes
Wrapper Classes 1) A wrapper class is a class whose object contains or wraps a primitive data type 2) When we create an object to a wrapper class, it contains a field and in this field, we can store a primitive data type 3) For example, if we create an object to Character wrapper class, it contains a single field char and it is possible to store a character like ‘a’ Need of Wrapper classes 1) Wrapper classes convert primitive data type into object and this is needed on internet to communicate between two applications 2) The classes in java.util package handle only objects hence wrapper classes help in this case also 498
Wrapper Classes 499
Wrapper Classes 500
Wrapper Classes Number class Number is an abstract class whose sub classes are Byte, Short,Integer,Long,Float and Double So the methods of Number class are commonly available in all these classes Methods of Number class byte byteValue() Converts the calling object into byte value short shortValue() Converts the calling object into short value int intValue() Converts the calling object into int value 501
Wrapper Classes long longValue() Converts the calling object into long value float floatValue() Converts the calling object into float value double doubleValue() Converts the calling object into double value Note The calling object can be an object of Byte, Short, Integer, Long, Float or Double class 502
Wrapper Classes Character Class The character class wraps a value of the primitive type char in an object. Character class has only one constructer which accepts primitive data type Character obj=new Character('A'); Important methods of Character class char charvalue ( ):used to convert character object into character primitive character obj=new character ('A'); char ch=obj charValue(); int compare To (character obj):useful to compare two character objects int x =obj1.compare (obj2); if obj1==obj2,returns 0 if obj1<obj2,returns negative value if obj1>obj2,returns positive value String toString( ):converts character object into string object 503
Wrapper Classes static Character value Of (char ch) convert a single character ch into character ch into character object static boolean isDigit (char ch) returns true if ch is a digit otherwise return false static boolean isLetter(char ch) returns true if ch is a letter static boolean isUpperCase(char ch) returns true if ch is a uppercase letter static boolean isLowerCase(char ch) returns true if ch is lower case letter 504
Wrapper Classes static boolean isSpaceChar(char ch) returns true if ch is represents a white space static boolean isLetterorDigit(char ch) returns true if ch either a letter or digit static char toUpperCase(char ch) converts ch into uppercase static char toLowerCase(char ch) converts ch into lowercase 505
Wrapper Classes Byte Class The byte class wraps a value of primitive type 'byte‘ in an object. Constructors 1)Byte(byte num): create byte object as Byte obj=new Byte(120); 2)Byte(String str): create Byte object by converting a string that contains a byte number Byte obj=new Byte("120"); 506
Wrapper Classes Important methods of Byte class int compareTo(Byte b) useful to compare the contents of Byte class objects. int x=obj1.comareTo(obj2); obj1==obj2 returns 0 obj1<obj2 returns negative value obj1>obj2 returns positive value boolean equals(object obj) compares the Byte object with any other object obj.If both have same content then it returns true otherwise false. static byte parseByte(String str) returns the primitive byte number contained in the string str. 507
Wrapper Classes String toString() converts Byte object into string object and returns that string object static Byte valueOf(String str) converts string str that contains some byte number into Byte class object static Byte valueOf(byte b) converts the primitive byte b into Byte object. 508
Wrapper Classes Short Class Short class wraps a value of primitive data type 'short' in its object. Constructors Short(short num) Takes short number as its parameter and convert it into Short class object. short s=14007; Short obj=new Short(s); Short(String str) Useful to construct the short class object by passing string str to it as String str="2756"; Short obj=new Short(str); 509
Wrapper Classes Important methods of Short class int compareTo(Short obj) Compare the numeric value of two short class objects and return 0,-ve value or +ve value. boolean equals(Object o) Compares the Short object with any other object o.if both have the same content then it returns true otherwise false. static short parseShort(String str) returns short equivalent of the string str. String toString() returns a string form of the Short object. static Short valueof(String str) Converts a string str that contains some short number into Short class object and returns that object. 510
Wrapper Classes Integer Class The integer class wraps a value of the primitive int number as its parameter and converts it into integer class object Constructors Integer(int num): creates integer object Integer obj= new Integer(123000); here, we are converting a primitive int value into integer object. This is called 'boxing’ Integer(String str): create an Integer object by converting a string that contains as int number Integer obj = new Integer("198663"); 511
Wrapper Classes Important methods of Integer class int compareTo(Integer obj) compares the numerical value of two integer class objects and returns 0,+ve value ,or -ve value boolean equals(object obj) compare the inter object with any other object if both have the same content,then it returns true otherwise false. static int parseInt(String str) returns int equivalent of the string str. String toString() returns a string form of the integer object. static Integer valueOf(String str) convert a string str that contains some int number into integer class object and returns that object. 512
Wrapper Classes static String toBinaryString(int i) converts decimal integer number i into binary umber system and returns that binary number as a string static String toHexString(int i) converts decimal integer number i into hexadecimal number system and returns that hexdecimal number as a string static String toOctalString(int i) converts decimal integer number i into octal number system and returns that octal number as a string int intValue() converts integer object into primitive int type value. This is called 'unboxing'. 513
Wrapper Classes Long Class The Long contains a primitive long type data Constructors Long(long num) Long object can be created Long obj=new Long(1230044); Long(String str) Create Long object by converting a string that contains a long number Strung str=“1230044”; Long obj=new Long(str); 514
Wrapper Classes Important methods of Long class int compareTo(Long obj) Compares the numeric value of two Long class objects and return 0, -ve value, or +ve value boolean equals(Object obj) Compares the Long object with any other object obj. If both have same content, then it returns true otherwise false static long parseLong(String str) Return long equivalent of the string str String toString() Converts Long object into String Object static Long valueOf(String str) Converts a string str that contains some long number into Long object 515
Wrapper Classes Math Class The class Math contains methods for performing basic numeric operations, such as the elementary exponential, square root etc.. All the methods of Math class are static Important methods of Math class static double sin(double arg) return the sine value of the arg Math.sin(0.5);//0.4794255 static double cos(double arg) return the cosine value of the arg Math.cos(0.5);//0.87758256189 static double tan(double arg) return the tanget value of the arg Math.tan(0.5);//0.54630248 516
Wrapper Classes static double log(double arg) return the natural logarithm value of the arg Math.log(0.5);//-0.69314718055 static double log10(double arg) return the base10 algorithm value of the arg Math.log10(0.5);//-0.30102999566 static double pow(double x, double n) return the x to the power of the n value Math.pow(5,3);//125.0 static double sqrt(double arg) return the square root of the arg Math.sqrt(25);//5.0 517
Wrapper Classes static double abs(double arg) return the absolute value of the arg . Absolute value present the positive quantity Math.abs(-4.55);//4.55 static double ceil(double arg) raises the given arg value to the next integer value. If integer is given to this method, it gives same value Math.ceil(4.5);//5.0 static double floor(double arg) decreases the given arg value to the previous integer value. If integer is given to this method, then it gives the same value, Math.floor(4.5); //4.0 static double min(arg1,arg2) returns the minimum of arg1 and arg2 Math.min(5,10); //5.0 518
Wrapper Classes static double max(arg1,arg2) returns the maximum of arg1 and arg2 Math.max(5,10); //10.0 static long round(arg) returns the rounded value of arg. If the fraction part of the number is more or equal to 0.5,then 1 is added to the integer part; otherwise the same integer part is returned. Math.round(4.6);//5 Math.round(4.4);//4 static double random() returns a random number between 0 and 1.A random number is a number that cannot be guessed by anyone. Math.random();//0.2230762209 519
Wrapper Classes static double toRadians(double angle) converts the given value in degree into radians. Math.toRadians(180);//3.141592653 static double to Degree(double angle) converts angle in radians into degree. Math.toDegree(3.14159);//179.9998479 520
Wrapper Classes Double class The Double class wraps a value of the primitive type double in an object. The double class object contains a double type field that stores a primitive double number Constructors Double (double num) Double object can be created double d=12.1223; Double obj=new Double(d); Double (String str) This constructor is useful to create a Double object by converting a string that contains a double number String str=“12.1223”; Double obj=new Double(str); 521
Wrapper Classes Important methods of Double class int compareTo(Double obj) Compares the numeric value of two Double class objects and return 0, - ve value, or +ve value boolean equals(Object obj) Compares the Double object with any other object obj. If both have same content, then it returns true otherwise false static double parseDouble(String str) Return double equivalent of the string str String toString() Converts Double object into String Object static Double valueOf(String str) Converts a string str that contains some double number into Double object 522
Wrapper Classes Float class The Float class wraps a value of the primitive type float in an object. The Float class object contains a float type field that stores a primitive float number Constructors Float (float num) Float object can be created float f=12.122f; Float obj=new Float(f); Float (String str) This constructor is useful to create a Float object by converting a string that contains a float number String str=“12.122f”; Float obj=new Float(str); 523
Wrapper Classes Important methods of Float class int compareTo(Float obj) Compares the numeric value of two Float class objects and return 0, -ve value, or +ve value boolean equals(Object obj) Compares the Float object with any other object obj. If both have same content, then it returns true otherwise false static float parseFloat(String str) Return float equivalent of the string str String toString() Converts Float object into String Object static Float valueOf(String str) Converts a string str that contains some float number into Float object 524
Wrapper Classes Boolean class The Boolean class wraps a value of the primitive type boolean in an object. The Boolean class object contains a boolean type field that stores a primitive boolean Constructors Boolean (boolean value) Boolean object can be created Boolean obj=new Boolean(true); Boolean (String str) This constructor is useful to create a Boolean object by converting a string that contains a boolean value String str=“false”; Boolean obj=new Boolean(str); 525
Wrapper Classes Important methods of Boolean class int compareTo(Boolean obj) Compares the value of two Boolean class objects and return 0, -ve value, or +ve value boolean equals(Object obj) Compares the Boolean object with any other object obj. If both have same content, then it returns true otherwise false static boolean parseBoolean(String str) Return boolean equivalent of the string str String toString() Converts Boolean object into String Object static Boolean valueOf(String str) Converts a string str that contains some boolean value into Boolean object 526
Wrapper Classes 527

Java2020 programming basics and fundamentals

  • 1.
  • 2.
    Programming Basics Procedural orProcedure Oriented Programming (POP) 1)Procedure Oriented Programming contains step by step procedure to execute. 2)Here, the problems get decomposed into small parts and then to solve each part one or more functions are used. 3)Thus in POP approach, the problem is viewed as a sequence of things to be done, such as, input taking, calculating and displaying. 2
  • 3.
    Programming Basics For example, Consideringthat we have to take two values from user and then to display the summation of the inputted values. In POP approach this problem may be decomposed as following, 1)First take an input and put it under one variable, here taking as a. 2)Then take another input and put it under another variable, here taking as b. 3)Now define a variable, such as c, as c = a + b. 4)Now display c. 3
  • 4.
  • 5.
    Difference between Compilerand Interpreter Interpreter Compiler Translates program one statement at a time. Scans the entire program and translates it as a whole into machine code. No intermediate object code is generated, hence are memory efficient. Generates intermediate object code which further requires linking, hence requires more memory. Continues translating the program until the first error is met, in which case it stops. Hence debugging is easy. It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. Programming language like Python, Ruby use interpreters. Programming language like C, C++ use compilers. 5
  • 6.
    Difference between Compilerand Interpreter 6
  • 7.
  • 8.
    8 Introduction To JAVA Unit# 2 : Introduction to Java What is Java? History Of Java Java Features Java Installation First Java Application Types of Java Applications Java Editions Java Software Components Interview Questions
  • 9.
    9 Introduction To JAVA Whatis JAVA? Java is simple, high performance, object-oriented, robust, secure, multi-threaded, and platform independent programming language to develop software that can be used for gaming, web, business, desktop, database, and other applications. Design goal of Java language project Write once, run anywhere (WORA) – that means java program can run anywhere and on any platform. When java code is compiled it is converted into byte code. Now this byte code is needed to run using JVM, no need of source code and recompilation.
  • 10.
    10 Introduction To JAVA HistoryOf Java 1.JAVA was developed by James Gosling and Patrick Naughton from Sun Microsystems Inc in 1991, later(2010) acquired by Oracle Corporation. 2.The design goal of Java is WORA(Write Once Run/Execute Anywhere) it means write a program once and then run this program on multiple operating systems. 3.The first publicly available version of Java (Java 1.0) was released in 1995 and the current of version of Java is Java SE11 released on September, 25th 2018
  • 11.
  • 12.
    12 Introduction To JAVA ImportantFeatures Of Java Simple 1)It does not use header files. 2)Eliminated the use of pointer and operator overloading. 3)Java is easy to learn and familiar because java syntax is just like c++. 4)There is a provision of Automatic Garbage Collection, in which there is no need to remove the unreferenced objects explicitly.
  • 13.
    Introduction To JAVA Compiledand Interpreted Usually, a computer language can be either compiled or interpreted. Java integrates the power of Compiled Languages with the flexibility of Interpreted Languages. Java compiler (javac) compiles the java source code into the bytecode. Java Virtual Machine (JVM) then executes this bytecode which is executable on many operating systems and is portable. 13
  • 14.
    14 Introduction To JAVA PlatformIndependent 1)Platform-independent means a program compiled on one machine can be executed on any machine in the world without any change. Java achieves platform independence by using the concept of the BYTE code. 2)The Java compiler never converts the source code to machine code like that of the C/C++ compiler. Instead, it converts the source code into an intermediate code called the byte code and this byte code is further translated to machine-dependent form by another layer of software called JVM (Java Virtual Machine). 3)Therefore, JVM can execute bytecode on any platform or OS on which it is present, regardless of the fact that on which machine the bytecode was generated. 4)This is where the “Write Once, run anywhere” (WORA) slogan for Java comes in, which means that we can develop applications on one environment (OS) and run on any other environment without doing any modification in the code.
  • 15.
  • 16.
    Introduction To JAVA Portable Youcan run Java bytecode on any hardware that has a compliant JVM which can convert the bytecode according to that particular machine. In Java, the size of the primitive data types is machine- independent, which were dependent in the case of C/C++. So, these provisions make Java programs portable among different platforms such as Windows, Unix, Solaris, and Mac. Moreover, any changes and updates made in Operating Systems, Processors and System resources will not enforce any changes in Java programs. 16
  • 17.
    17 Introduction To JAVA ObjectOriented Programming Language 1)Object oriented programming is a way of organizing programs as collection of objects, each of object represents an instance of a class. 2)Java programs also organizing collection of classes and objects so Java is called as object oriented programming language
  • 18.
    18 Introduction To JAVA Robust Robustmeans inbuilt capabilities to handle errors/exceptions. Java is robust because of following 1)Built-in Exception handling. 2)Strong type checking i.e. all data must be declared an explicit type. 3)Automatic garbage collection. 4)First checks the reliability of the code before Execution etc.
  • 19.
    19 Introduction To JAVA Secure Javaprograms run within the JVM which protects from unauthorized access to system resources. That’s why several security flaws like stack corruption or buffer overflow is impossible to exploit in Java.
  • 20.
    20 Introduction To JAVA Multithreading Javasupports multithreading. Multithreading is a feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU.
  • 21.
    21 Introduction To JAVA Distributed Thisfeature in Java gives the advantage of distributed programming, which is very helpful when we develop large projects. Java helps us to achieve this by providing the concept of RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans). In Java, we can split a program into many parts and store these parts on different computers. A Java programmer sitting on a machine can access another program running on the other machine. Java comes with an extensive library of classes for interacting, using TCP/IP protocols such as HTTP and FTP, which makes creating network connections much easier than in C/C++. It also enables multiple programmers at many locations to work together on a single project.
  • 22.
    22 Introduction To JAVA ArchitecturalNeutral Architectural neutral means that the program written on one platform is independent of other platforms and can run on any other platform without recompiling them. Byte-code is not dependent on any machine architecture and Java Virtual Machine (JVM) can easily translate bytecode into a machine-specific code. Dynamic The process of allocating the memory space to the input of the program at a run-time is known as dynamic memory allocation. In Java memory allocation happened at run-time with the help of 'new' operator. So Java is dynamic
  • 23.
    23 Introduction To JAVA Highperformance Java provides high performance with the use of “JIT – Just In Time compiler”, in which the compiler compiles the code on-demand basis, that is, it compiles only that method which is being called. This saves time and makes it more efficient. Java architecture is also designed in such a way that it reduces overheads during runtime. The inclusion of multithreading enhances the overall execution speed of Java programs. Bytecodes generated by the Java compiler are highly optimized, so Java Virtual Machine can execute them much faster.
  • 24.
    24 Introduction To JAVA ComponentsOf Java Software Java Development Kit (JDK) Java Development Kit contains two parts. One part contains the utilities like javac, debugger and some jar files which helps in compiling the source code (.java files) into byte code (.class files) and debug the programs. The other part is the JRE, which contains the utilities like java which help in running/executing the byte code. If we want to write programs and run them, then we need the JDK installed.
  • 25.
    25 Introduction To JAVA JavaRun-time Environment (JRE) Java Run-time Environment helps in running the programs. JRE contains the JVM, the java classes/packages and the run-time libraries. If we do not want to write programs, but only execute the programs written by others, then JRE alone will be sufficient.
  • 26.
    26 Introduction To JAVA JavaVirtual Machine (JVM) Java Virtual Machine is important part of the JRE, which actually runs the programs (.class files), it uses the java class libraries and the run-time libraries to execute those programs. Every operating system(OS) or platform will have a different JVM.
  • 27.
    27 Introduction To JAVA JustIn Time Compiler (JIT) JIT is a module inside the JVM which helps in compiling certain parts of byte code into the machine code for higher performance.
  • 28.
  • 29.
    29 Introduction To JAVA EditionsOf Java Software JavaSE (Java Standard/Software Edition) JavaSE is mainly used to create applications for Desktop environment. It consist all the basics of Java the language, variables, primitive data types, Arrays, Streams, Strings Java Database Connectivity(JDBC) and much more.
  • 30.
    30 Introduction To JAVA JavaEE(JavaEnterprise Edition) The enterprise edition of Java has a much larger usage of Java, like development of web applications, networking, server side scripting and other various web based applications. JavaEE uses many components of JavaSE, as well as, has many new features of it’s own like Servlets, JavaBeans, Java Message Services etc,.
  • 31.
    31 Introduction To JAVA JavaME(Java Micro/Mobile Edition) This version of Java is mainly concentrated for the applications running on embedded systems, mobiles wireless devices, set top boxes etc. Old Nokia phones, which used Symbian OS, used this technology.
  • 32.
  • 33.
    33 First Java Application StepsTo Write First Java Program Step 1:Decalre the class Every java application must have at least one class definition that consists of class keyword followed by class name. public class FirstJavaProgram { }
  • 34.
    34 First Java Application Step2: Declare the main() method To execute the above class JVM need one entry point in the class that entry point is main()method having signature as shown below public static void main(String[] args) { }
  • 35.
    35 First Java Application public– access modifier, meaning global visibility static – the method can be accessed straight from the class, we don’t have to instantiate an object to have a reference and use it void – means that this method doesn’t return a value main – the name of the method, that’s the identifier JVM looks for when executing a Java program args parameter, it represents the values received by the method.
  • 36.
    36 First Java Application Step3: Write logic Write some logic or statement to generate simple response as shown below System.out.println("This is my first program in java");
  • 37.
  • 38.
    38 First Java Application Step4:Save The File We should always save the file same as the public class name. In our program, the public class name is FirstJavaProgram, that’s why our file name should be FirstJavaProgram.java.
  • 39.
    39 First Java Application Step5: Compile The Program We will compile the program. For this, open command prompt (cmd) on Windows type the following command and hit enter. javac FirstJavaProgram.java Stpe 6: Execute The Program After compilation the .java file gets translated into the .class file(byte code). Now we can run the program. To run the program, type the following command and hit enter: java FirstJavaProgram
  • 40.
    40 First JAVA Application JavaCompilation And Execution 1)In the Java programming language, all source code is first written and save with the .java extension. 2)After compilation, .class files are generated by javac compiler. 3) A .class file contain byte code that is not natural to your processor, this byte code convert into processor understandable code by JVM
  • 41.
    41 First JAVA Application JavaCompilation and Execution
  • 42.
  • 43.
    Naming Conventions InJava Identifiers A name in the program is an identifier it may be class name or method name, variable name or label name. Example Class Test{ public static void main(String[] args) { int x=10 System.out.println(x); } 43
  • 44.
    Naming Conventions InJava Rules for defining Identifiers 1)Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). 2)Identifiers cannot start with a number 3)After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers. 4)In practice, there is no limit to the number of characters an identifier can contain. 5)You can't use a Java keyword as an identifier. 6)Identifiers in Java are case-sensitive; foo and FOO are two different identifiers. 44
  • 45.
    Naming Conventions InJava Coding standards for classes Usually class name should be noun. Should starts with upper case letter and if it contain multiple words every inner words also should start with capital letters. Example: String StringBuffer NumberFormat CustomerInformation 45
  • 46.
    Naming Conventions InJava Coding standards for Interfaces Usually interface named should be adjective, starts with capital letters and if it contains multiple words, every inner word also should starts with capital letter. Example: Runnable Serializable Clonable Movable Transferable Workable 46
  • 47.
    Naming Conventions InJava Coding standards with methods Values should be either verbs or verb + noun combination. Starts with lower case and every inner words starts with upper case(this convention is also called camel case convention). Example: getName(), getMessage(), toString(), show(), display(). 47
  • 48.
    Naming Conventions InJava Coding standards for variables Usually the variable starts with noun and every inner word should start with upper case i.e camel case convention. Example: name, rollNo, bandwidth, totalNumber. 48
  • 49.
    Naming Conventions InJava Coding standards for constants It should be noun, it should contain only upper case letters and works are separated with underscores. Example: MAX_SIZE, MIN_PRIORITY, COLLEGE_NAME. 49
  • 50.
    Data types, Literalsand Variables in Java
  • 51.
    Data types inJava Data type In computer science, a data type is an attribute of data that tells the compiler or interpreter how the programmer aims to use the data. Java Data Types 1)Primitive Data Types 2)Non-Primitive DataTypes Primitive Data Types As the name suggests, the programming language pre-defines the primitive data types. Primitive types are the most basic data types available in Java. There are 8 primitive data types in Java: byte, char, short, int, long, float, double and boolean. Primitive data types have a constraint that they can hold data of the same type and have a fixed size. 51
  • 52.
  • 53.
    Data types inJava Non-Primitive Data Types/ Referenced Data Types 1)The term non-primitive data type means that these types contain “a memory address of the variable”. 2)In contrast to primitive data types, which are defined by Java, non-primitive data types are not defined or created by Java but they are created by the programmers. They are also called Reference data types because they cannot store the value of a variable directly in memory. 3)Non-primitive data types do not store the value itself but they store a reference or address (memory location) of that value. 53
  • 54.
    Data types inJava Java Integers It can hold whole numbers such as 196, -52, 4036 etc. Java supports four different types of integers These are: 54
  • 55.
  • 56.
  • 57.
  • 58.
    Single precision floatingpoint number Single precision uses 32 bit to represent a floating point number. First bit represent the sign of the number, negative or positive. Next 8 bits are used to store the exponent of the number. This exponent can be signed 8-bit integer ranging from -127 – 128 of signed integer (0 to 255). And the left 23 bits are used to represent the fraction part and are called fraction bits. 8 exponent bits provide us with the range and 23 bits provide us with the actual precision. 58
  • 59.
    Double precision floatingpoint number Double precision uses 64 bits to represent a value. First bit is used for the same purpose as in single point precision i.e., represents sign of the number. Next 11 bits are used to denote exponent, which provide us with the range, and has 3 more bits than single precision, so it is used to represent a wider range of values. Next 52 bits are used to represent the fractional part which is 29 bits more than binary32 bit representation scheme. So it has a greater precision than single precision. 59
  • 60.
    Data types inJava 60 Floating-Point Literals in Java Here, datatypes can only be specified in decimal forms and not in octal or hexadecimal form.
  • 61.
    Data types inJava Java Characters A character is used to store a ‘single’ character. A single quote must surround a character. The valid Character type is char. In Java, a character is not an 8-bit quantity but here character is represented by a 16-bit Unicode. 61 Syntax char myChar = ’A’ ; Size 2 bytes(16 bits) Values A single character representing a digit, letter, or symbol. Default Value ‘u0000’ (0) Range u0000’ (0) to ‘uffff’ (65535)
  • 62.
    Data types inJava Char Literals in Java These are the four types of char Single Quote Java Literal can be specified to a char data type as a single character within a single quote. char ch = 'a'; Char as Integral A char literal in Java can specify as integral literal which also represents the Unicode value of a character. Furthermore, an integer can specify in decimal, octal and even hexadecimal type, but the range is 0-65535. char ch = 062; 62
  • 63.
    Data Types inJava Unicode Representation Char literals can specify in Unicode representation ‘uxxxx’. Here XXXX represents 4 hexadecimal numbers. char ch = 'u0061';// Here /u0061 represent a. Escape Sequence Escape sequences can also specify as char literal. 63
  • 64.
    Data types inJava boolean • boolean data type represents one bit of information as either true or false. i.e. there is only two possible value true or false. Internally, JVM uses one bit of storage to represent a boolean value. • It is generally used to test a particular conditional statement during the execution of program. • boolean data type takes zero bytes of memory. • Default value is false. For example: boolean b = false; 64
  • 65.
    Variables in Java Variablesin Java A variable in Java is a kind of container that contains the value during program execution. Variable is a basic unit of storage in a program that represents reserved storage locations, whose values can be manipulated during the execution of a program. Declaration of a Variable To declare the variable, we must specify the data type followed by the unique name of the variable. Syntax: dataType variableName Example: double payRate ; 65
  • 66.
    Variables in Java Initializationof a Variable Syntax: variableName = value ; Example: payRate = 2500; Combining the declaration and initialization, we can write dataType variableName = value ; Example: double area = 378.87 ; 66
  • 67.
  • 68.
    Variables in Java Namingconventions for variables 1)The variable names cannot contain white spaces, for example, long dist ance = 1000; is invalid because the variable name has a space in it. 2)A variable name can begin with a special character dollar ($) and underscore ( _ ). 3)The first letter of a variable cannot be a digit. 4)A variable name should begin with a lowercase letter, for example, int number. For lengthy variable names having more than one word, we can use camelCase, for example, int salaryPerDay; float rateOfInterest; ,etc. are valid. 5)We cannot use keywords like int, for, while, class, etc as a variable name. 6)Variable names are case-sensitive in Java. 68
  • 69.
    Type Promotion inJava Type Promotion in Java There are several type promotion rules in Java that are followed while evaluating expressions- 1)All byte, short and char values are promoted to int. 2)If any operand is long then the expression result is long. i.e. whole expression is promoted to long. 3)If any operand is a float then the expression result is float. i.e. whole expression is automatically promoted to float. 4)If any operand is a double then the expression result is double. i.e. whole expression is promoted to double in Java. 69
  • 70.
    Type Promotion inJava When one of the operand is double. int i = 30; double d = 2.5; double result = i * d; When one of the operand is float. short s = 4; int i = 30; float f = 6.75f; float result = (s+i) * f; 70
  • 71.
  • 72.
    Type Casting inJava What is Type Casting or Type Conversion Type Conversion or Type Casting is the process of converting a variable of one predefined type into another. If these data types are compatible with each other, the compiler automatically converts them and if they are not compatible, then the programmer needs to typecast them explicitly. 72
  • 73.
    Type Casting inJava Types of Type Conversion 1)Implicit Type Conversion 2)Explicit Type Conversion 73
  • 74.
    Type Casting inJava Implicit Type Conversion Implicit Type Conversion or Automatic type conversion is a process of automatic conversion of one data type to another by the compiler. This process is also called Widening Conversion because the compiler converts the value of narrower (smaller size) data type into a value of a broader (larger size) data type without loss of information. The implicit data type conversion is possible only when 1)The two data types are compatible with each other. 2)There is a need to convert a smaller or narrower data type to the larger type size. For example, the compiler automatically converts byte to short because the byte is smaller ( 8 bits ) or narrower than short ( 16 bits ). 74
  • 75.
  • 76.
    Type Casting inJava Explicit Type Conversion The Explicit Type Conversion is a process of explicitly converting a type to a specific type. We also call it Narrowing Conversion. The typecasting is done manually by the programmer, and not by the compiler. We need to do explicit or narrowing type conversion when the value of a broader (higher size) data type needs to be converted to a value of a narrower (lower size) data type. For example, double data type explicitly converted into int type. 76
  • 77.
    Type Casting inJava The following is the syntax of typecasting in Java (type) expression; Where type is a valid data type to which the conversion is to be done. For example, if we want to make sure that the expression (x / y + 5) evaluates to type float, we will write it as, (float)(x / y +5); 77
  • 78.
  • 79.
  • 80.
  • 81.
    Operators in Java Incomputer programming, an operator is a special symbol that is used to perform operations on the variables and values. The operators represent the operations (specific tasks) and the objects/variables of the operations are known as operands. 81
  • 82.
    Operators in Java Typesof Operators 82
  • 83.
    Operators in Java ArithmeticOperators Java provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division, and the remainder which are +, -, *, /, and % respectively. Each of these is a binary operator that is, it requires two values (operands) to perform calculations. 83
  • 84.
    Operators in Java RelationalOperators Java provides 6 relational operators for comparing numbers and characters. But, relational operators do not work with strings. After the comparison, they return the result in boolean datatype. If the comparison is true, the relational operator results in true, otherwise false. 84
  • 85.
  • 86.
    Operators in Java LogicalOperators Logical operators are also known as conditional operators. These operators are used for evaluating one or more boolean expression, for complex decision-making. They also return a boolean value (true or false). There are three types of logical or conditional operators in Java are && (Logical-AND), || (Logical-OR) and ! (Logical NOT).types of logical or conditional operators In this, && (Logical-AND) and || (Logical-OR) operators are the binary logical operators that work on two operands or expressions, while ! (Logical NOT) is a unary logical operator which works on single operand or expression. 86
  • 87.
  • 88.
    Operators in Java 1)A Logical-AND (&&) evaluates the left side of the operation first (operand one), and if it resolves to false, the && operator doesn't bother looking at the right side of the expression (operand two) since the && operator already knows that the complete expression can't possibly be true. 2) The Logical-OR(||) operator is similar to the && operator, except that it evaluates to true if EITHER of the operands is true. 3) If the first operand in an OR operation is true, the result will be true, so the short-circuit || doesn't waste time looking at the right side of the equation. 4) If the first operand is false, however, the short-circuit || has to evaluate the second operand to see if the result of the OR operation will be true or false. 88
  • 89.
    Operators in Java Thelogical NOT operator, which is written as ! , is a unary operator that works on a single operand or expression. The Logical NOT operator (!) negates or reverses the truth value of its operand. That is if the expression is true, then !expression is false and vice- versa. ! (9 != 0) //results into false because 9 is non-zero(i.e., true). ! (6 > 2) //results into false because the expression 6 > 2 is true. ! (4 > 10) //results into true because the expression 4 > 10 is false. 89
  • 90.
    Operators in Java BitwiseOperators in Java The Bitwise operators manipulate the individual bits of a number. The bitwise operators work with the integer types that is, byte, short, int, and long types. Java provides 4 bitwise operators: 90
  • 91.
  • 92.
    Operators in Java BitwiseNOT( ~ ) The Bitwise NOT is represented by the symbol (~) . Bitwise NOT is an unary operator and inverts all the bits represented by its operand. That is, 0s become 1s and 1s become byte a = 3;//00000011 byte b = (byte)~a;//11111100 System.out.println("Value of b = "+b);//-4 92
  • 93.
  • 94.
    Operators in Java TheBitwise AND Operator (&) The bitwise AND operator, &, produces a 1 bit if both the operands are also 1. A zero is produced in all the other cases. Example 00101010 42 &00001111 15 _________ 00001010 10 94
  • 95.
    Operators in Java TheBitwise OR Operator The bitwise OR operator, |, combines bits such that if either of the bits in the operands is 1, then the resultant bit is 1. Example 00101010 42 |00001111 15 _________ 00101111 47 95
  • 96.
    Operators in Java TheBitwise XOR Operator The bitwise XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1. Otherwise, the result is zero. Example 00101010 42 ^00001111 15 _________ 00100101 37 96
  • 97.
    Operators in Java Javaternary(?) Operator Ternary (three-way) operator can replace certain types of if-then-else statements. general form expression1 ? expression2 : expression 3 Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. int i, k; i = 10; k = i < 0 ? -i : i; // get absolute value of i System.out.println("Absolute value of " + i + " is " + k);//10 i = -10; k = i < 0 ? -i : i; // get absolute value of i System.out.println("Absolute value of " + i + " is " + k);//-10 97
  • 98.
    Operators in Java Javainstanceof Operator The instanceof operator in Java, used only for the object reference variables. This operator basically checks whether the object is of a specific type (class or interface type). general form (Object reference variable) instanceof (class/interface type) String str_name = "James"; boolean res = str_name instanceof String; System.out.println(res); 98
  • 99.
  • 100.
    Control Statements inJava Control Statements in Java The statements those who control the order of execution of a program are known as control statements Types of control statements 1)Selection/Decision making Statements Using these statements, a piece of code would be executed only if a certain condition(s) is true. 2)Iteration statements Using these statements to iterate a block of code repeatedly until the condition is false 3) Jump statements Using these statements to skip the statements and come-out from those. 100
  • 101.
  • 102.
    Control Statements inJava The if-else control statement The if-else statement is used to choose & execute any one action among two. Syntax if(condition){ // group of programming statements } else{ // group of programming statements } Braces in the if-else and other control statements are optional if we used only one statement for every action If the condition present inside the parentheses is true, if-block is executed. After execution of if-block, program control skips else-block and jumps directly to the statements after else-block. If the condition inside the parenthesis is false, else-block is executed by skipping if-block 102
  • 103.
  • 104.
    Control Statements inJava if statement (if without else statement) It is possible to use if statement without the else statement. Syntax if(condition){ // group of // programming // statements } If the condition inside parentheses is true, if-block is executed. After execution of if-block, program control executes statements after it. If the condition inside the parenthesis is false, if-block is skipped, and statements after it are executed. 104
  • 105.
  • 106.
    Control Statements inJava Nested if statement In Java programming, it is possible to place if control statement inside another if-block or else-block. if(condition1){ // outer if-block if(condition2){ block1 } } else { // outer else-block if(condition3){ block2 } } In the above example, if condition1 becomes true, program control enters into outer if-block. Then it checks for condition2. If condition2 is true, block1 is executed. After execution of block1, control is transferred directly to the statement after the outer else- block. If condition1 becomes false, program control enters into outer else-block skipping outer if- block. Then it checks for condition3. If condition3 is true, block2 is executed. After execution of block2 and outer else-block control is transferred directly to statement after 106
  • 107.
  • 108.
    Control Statements inJava 108 Program to find bigger number among three given number if(a>b){//’a’ is bigger if(a>c)//’a’ is already bigger than ‘b’ so the comparison with ‘c’ only ‘a’ is bigger else ‘c’ is bigger }//outer if else{ if(b>c)//compare to ‘a’ ‘b’ is bigger control comes to here. Comparison with ‘c’ only ‘b’ is bigger else ‘c’ is bigger } a=12, b=14, c=11
  • 109.
    Control Statements inJava 109 Program to find out the given year is leap year or not? Logic: A centennial (divisible by 100) year is leap if it is divisible by 400, and a non-centennial year is leap if it is divisible by 4. if(year %100!=0){ if(year%4==0) leap year else not a leap year } else{ if(year%400==0) leap year else not a leap year } Solution with if-else -------------------------- if(year%100!=0 && year %4==0 || year%400==0) leap year else not a leap year
  • 110.
    Control Statements inJava 110 Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count. public int luckySum(int a, int b, int c) { } For example, luckySum(1, 2, 3) → 6 luckySum(1, 2, 13) → 3 luckySum(1, 13, 3) → 1 luckySum(13, 5, 3) → 0
  • 111.
    Control Statements inJava 111 luckySum solution public int luckySum(int a, int b, int c) { if (a == 13) return 0; else if (b == 13) return a; else if (c == 13) return a + b; else return a + b +c; }
  • 112.
    Control Statements inJava 112 When bachelor's get together for a party, they like to have beers. A bachelor party is successful when the number of beers is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of beers. Return true if the party with the given values is successful, or false otherwise. public boolean beerParty(int beers, boolean isWeekend) { } beerParty(30, false) → false beerParty(50, false) → true beerParty(70, true) → true beerParty(30, true) → false
  • 113.
    Control Statements inJava 113 beerParty solution public boolean beerParty(int beers, boolean isWeekend) { if (isWeekend == true && beers >= 40) return true; if (!(isWeekend) && beers >=40 && beers<= 60) return true; else return false; }
  • 114.
    Control Statements inJava 114 We are having a party with amounts of tea and candy. Return the int outcome of the party encoded as 0=bad, 1=good, or 2=great. A party is good (1) if both tea and candy are at least 5 rating. However, if either tea or candy is at least double the amount of the other one, the party is great (2). However, in all cases, if either tea or candy is less than 5 rating, the party is always bad (0). public int teaParty(int tea, int candy) { } teaParty(6, 8) → 1 teaParty(3, 8) → 0 teaParty(20, 6) → 2
  • 115.
    Control Statements inJava 115 teaParty solution public int teaParty(int tea, int candy) { if (tea < 5 || candy < 5) return 0; if ((tea >= 2 * candy) || (candy >= 2 * tea)) return 2; else return 1; }
  • 116.
    Control Statements inJava The if-else-if ladder statement The if-else-if ladder is a very common programming constructs in Java, which is also called the if-else-if staircase because of its appearance. We can use many if-else-if statements in our program. The general form or syntax of the if-else-if ladder statement is: if( expression1) statement1 ; else if(expression2) statement2; . . else statement3; 116
  • 117.
  • 118.
    Control Statements inJava The switch statement In Java programming, the switch statement is used to make a specific selection from multiple cases. Syntax switch(expression){ case constant_value_1 : statements to be executed; break; case constant_value_2 : statements to be executed; break; case constant_value_N : statements to be executed; break; case default : statements to be executed; } 118
  • 119.
    Control Statements inJava 1) In a switch statement, the expression inside switch’s left & right parenthesis is executed first. 2) If any case matches the expression value, program control jumps directly to that case and statements of that case are executed. 3) If expression value does not match with any case, then program control jumps directly to the default case and statements of default case are executed. 119
  • 120.
  • 121.
  • 122.
    Control Statements inJava The for loop Syntax for(initialization;condition;update){ // programming // statements } The for loop consists of three expressions called initialization, condition & update and its body (statements inside curly braces). 122
  • 123.
  • 124.
    Control Statements inJava The while loop Same as for loop, while loop is used to execute specific part of the program repeatedly. Syntax while(condition){ // programming // statements } 124
  • 125.
  • 126.
    Control Statements inJava The do-while loop Same as for loop and while loop, do-while loop is also used to execute specific part of the program repeatedly. The only difference is that the body of do-while loop is executed at least once even if the condition is false. Syntax do{ // programming // statements }while(condition); 126
  • 127.
  • 128.
    Control Statements inJava The break statement The statement that is used to break/stop the flow of loops & switch statement is known as break statement. Inside the loop, break statement terminates the loop execution when it is encountered. Inside switch statement, break statement is used to jump out of the switch statement instantly when it is encountered. Syntax break; Java Programming Language break Statement Working in for, while and do-while loops After terminating a loop by using the break statement, program control is transferred immediately to the statement after the loop. 128
  • 129.
  • 130.
    Control Statements inJava The continue statement The continue statement forces loop to skip statements written after it & continue next execution of the loop. Syntax continue; Note If the continue statement is encountered in the for loop, program control jumps directly to the update expression. If the continue statement is encountered in the while & do-while loops, program control jumps directly to the condition. 130
  • 131.
  • 132.
  • 133.
  • 134.
    Arrays In Java 1)In Java array is an object which store multiple variables of the same type. It can hold primitive types as well as object references. Since array is an object, it is created during runtime .The array length is fixed. 2) Array is an index based data structure so it allow random access to elements, they store. Indices start with '0' 134
  • 135.
    Arrays In Java Featuresof an Array 1)Array is an object so we can find the length of the array using attribute 'length'. 2)Array is an ordered and each have an index beginning from '0' for the first element. 3)Arrays can store primitives as well as objects. But all must be of a single type in one array instance. 4)Just like other variables so can used as method arguments. 5)The size of an array must be specified by an int value. 135
  • 136.
  • 137.
    Arrays In Java ArrayDeclaration The declaration of array states the type of the element that the array holds followed by the square braces and identifier which indicates the identifier is array type. Example Declaring an array which holds elements of integer type. 137
  • 138.
    Arrays In Java Differentway of declaring an array 138
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
    Arrays In Java Accessingelements from an array by using index value After the array is created, its elements can be accessed by their index. The index is a number placed inside square brackets which follow the array name. Example, String[] names = {"Jane", "Thomas", "Lucy", "David"}; System.out.println(names[0]); System.out.println(names[1]); System.out.println(names[2]); System.out.println(names[3]); 147
  • 148.
    Arrays In Java Accessingelements from an array by using for each loop J2SE 5 introduces special type of for loop called foreach loop to access elements of array. Using foreach loop you can access complete array sequentially without using index of array. Example, int[] arr = {10, 20, 30, 40}; for(int x : arr){ System.out.println(x); } 148
  • 149.
    Arrays In Java Accessingelements from an array by using basic for loop Example, String[] planets = { "Mercury", "Venus", "Mars", "Earth", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" }; for (int i=0; i < planets.length; i++) { System.out.println(planets[i]); } 149
  • 150.
    Arrays In Java Anonymousarrays You can create an array without specifying any name such arrays are known as anonymous arrays. Since it doesn’t have name to refer you can use it only once in your program. Generally, anonymous arrays are passed as arguments to methods. You can create an anonymous array by initializing it at the time of creation. For example, new int[] { 1254, 5452, 5743, 9984}; //int array new String[] {"Java", "JavaFX", "Hadoop"}; //String array 150
  • 151.
    Arrays In Java publicclass AnonymousArray { public static void arrayToUpperCase(String [] array) { for(int i=0; i< array.length; i++) { char[] ch = array[i].toCharArray(); for(int j=0; j<ch.length; j++){ ch[j] = Character.toUpperCase(ch[j]); } System.out.println(new String(ch)); } } public static void main(String args[]) { arrayToUpperCase(new String[] {"Krishna", "Vishnu", "Dhana", "Rupa", "Raja", "Kavya"}); }} 151
  • 152.
    Arrays In Java Two-dimensionalArrays The Two Dimensional Array in Java programming language is nothing but an Array of Arrays. In Java Two Dimensional Array, data stored in row and columns, and we can access the record using both the row index and column index 152
  • 153.
    Arrays In Java Example, Twodimensional array: int[][] twoDarr = new int[10][20]; Three dimensional array: int[][][] threeDarr = new int[10][20][30]; The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements. 153
  • 154.
    Arrays In Java Declarationof 2D array Data_Type[][] Array_Name; Example : int [][] anIntegerArray; Create Two dimensional Array in Java In order to create a two dimensional array in Java, we have to use the New operator as we shown below: Data_Type[][] Array_Name = new int[Row_Size][Column_Size]; Example : anIntegerArray = new int[3][4]; It is a 2-dimensional array, that can hold a maximum of 12 elements, 154
  • 155.
  • 156.
    Arrays In Java Declarationand Initialization of 2D array Syntax data_type[][] array_name = { {valueR1C1, valueR1C2, ....}, {valueR2C1, valueR2C2, ....} }; For example, int[][] arr = {{1, 2}, {3, 4}}; 156
  • 157.
    Arrays In Java Retrieveelements from 2D arrays standard method int[][] a={{10,20},{30,40}};//declaration and initialization System.out.println("Two dimensional array elements are"); System.out.println(a[0][0]); System.out.println(a[0][1]); System.out.println(a[1][0]); System.out.println(a[1][1]); 157
  • 158.
    Arrays In Java Retrieveelements from 2D array by using for loop int[][] a={{10,20},{30,40},{50,60}};//declaration and initialization System.out.println("Two dimensional array elements are"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++){ System.out.println(a[i][j]); } } 158
  • 159.
    Arrays In Java Dynamicallypassing row and column sizes Scanner sc=new Scanner(System.in); System.out.println("Enter Row length of an array : "); int row=sc.nextInt(); System.out.println("Enter column length of an array : "); int column=sc.nextInt(); int a[][]=new int[row][column];//declaration 159
  • 160.
    Arrays In Java System.out.print("Enter" + row*column + " Elements to Store in Array :n"); for (int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ a[i][j] = sc.nextInt(); } } 160
  • 161.
    Arrays In Java System.out.print("Elementsin Array are :n"); for (int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ System.out.println("Row ["+i+"]: Column ["+j+"] :"+a[i][j]); } } 161
  • 162.
    Arrays In Java JaggedArray in Java Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays. int arr[][] = new int[2][]; // Declaring 2-D array with 2 rows // Making the above array Jagged arr[0] = new int[3]; // First row has 3 columns arr[1] = new int[2]; // Second row has 2 columns 162
  • 163.
    Arrays In Java //Initializing array int count = 0; for (int i=0; i<arr.length; i++) for(int j=0; j<arr[i].length; j++) arr[i][j] = count++; // Displaying the values of 2D Jagged array System.out.println("Contents of 2D Jagged Array"); for (int i=0; i<arr.length; i++) { for (int j=0; j<arr[i].length; j++) System.out.print(arr[i][j] + " "); System.out.println(); } 163
  • 164.
    Abstraction In Java Inobject oriented programming abstraction is a process of providing functionality to the users by hiding its implementation details from them In other words, the user will have just the knowledge of what an entity is doing instead of its implementation 164
  • 165.
    Abstraction In Java Reallife example of Abstraction is ATM Machine; All are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about ATM. 165
  • 166.
  • 167.
    Abstraction In Java Howto Achieve Abstraction in Java? In Java, we can achieve Data Abstraction using Abstract class and Interface Interface allow 100% abstraction(complete abstraction). Interface allow you to abstract the implementation completely Abstract class allow 0 to 100% abstraction (partial to complete abstraction)because abstract class can contain concrete methods that have the implementation which results in a partial abstraction 167
  • 168.
    Abstraction In Java InJava programming we have two types of classes they are 1)Concrete class 2)Abstract class A concrete class is one which is containing fully defined methods or implemented method. class Helloworld{ void display(){ System.out.println("Good Morning........"); } } 168
  • 169.
    Abstraction In Java Abstractclass A class that is declared with abstract keyword, is known as abstract class. An abstract class is one which is containing some defined method and some undefined method. In java programming undefined methods are known as un-Implemented, or abstract method. Syntax abstract class className{ ...... } Example abstract class A{ ..... 169
  • 170.
    Abstraction In Java Abstractmethod An abstract method is one which contains only declaration or prototype but it never contains body or implementation. In order to make any method as abstract whose declaration is must be predefined by abstract keyword. The declaration of an abstract method must end with a semicolon; Syntax abstract ReturnType methodName(List of formal parameter); Example abstract void Bike(); 170
  • 171.
    Abstraction In Java Rulesfor Using Abstract Class in Java 1)We can declare an abstract class using the abstract keyword. 2)It may have abstract as well as concrete (non-abstract) methods. 3)An abstract class can have static methods. 4)An abstract class can also have constructors. 5)It can have final methods. If we declare the method as final inside the abstract class then the subclass can not change the body of the method. 171
  • 172.
    Abstraction In Java 6)We can’t instantiate or create an object of an abstract class. 7) A class derived from the abstract parent class must implement each method that is declared as abstract in the parent class. Otherwise, there will be a compilation error. 8) If the derived class does not implement all the abstract methods of an abstract parent class, then the derived class must also declare itself as abstract. 172
  • 173.
    Abstraction In Java Whydo we need Abstract Classes in Java? We want to create a class that just declares the methods without providing a complete implementation of every method. And, we want that this method(s) is shared by all of its child classes, and all the implementation details will be filled by these subclasses. Let’s take the example of a banking application or software. Suppose we have a class BankAccount that has a method deposit() and withdraw() and the subclasses of it like SavingsAccount, CurrentAccount, FixedDepositAccount, etc. Since the process of deposit and withdrawal differs from one account to another, there is no point to implement these two methods in the parent class BankAccount. This is because every child class must override these methods and provide an implementation of them. 173
  • 174.
  • 175.
    Abstraction In Java InterfaceIn Java 1)In Java, an interface is a blueprint or template of a class used to achieve 100%abstraction. 2)When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. 3)There can be only abstract methods in an interface. 4)If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract. 175
  • 176.
    Abstraction In Java Syntaxto create an interface interface interface-name{ //abstract methods } Example interface Animal{ public void eat(); public void travel(); } 176
  • 177.
    Abstraction In Java Whywe do use interface? 177
  • 178.
    Abstraction In Java Propertiesof a Java Interface 1)An interface is implicitly abstract. While declaring an interface, you do not need to use the keyword abstract. 2)Each method of an interface is implicitly public and abstract, so we need not use the public and abstract keyword while declaring methods inside an interface. The following five method declarations are legal and identical a)void bounce(); b)public void bounce(); c)abstract void bounce(); d)public abstract void bounce(); e)abstract public void bounce(); 178
  • 179.
    Abstraction In Java 3)All variables defined in an interface are public, static, and final. In other words, interfaces can declare only constants, not instance variables. Legal interface constants declarations a) public int x = 1; // Looks non-static and non-final, // but isn't! b) int x = 1; // Looks default, non-final, // non-static, but isn't! c) static int x = 1; // Doesn't show final or public d) final int x = 1; // Doesn't show static or public e) public static int x = 1; // Doesn't show final f) public final int x = 1; // Doesn't show static g) static final int x = 1 // Doesn't show public 179
  • 180.
  • 181.
    Abstraction In Java 4)An interface can extend one or more other interfaces. 5) A class can extend only one class (no multiple inheritance), but it can implement one or more interfaces. 181
  • 182.
    Abstraction In Java 182 1)class Foo { } class Bar implements Foo { } 2) interface Baz { } interface Fi { } interface Fee implements Baz { } 3) class Foo { } interface Zee implements Foo { } 4) class Foo interface Zoo extends Foo { }
  • 183.
    Abstraction In Java 5)interface Fi { } interface Boo extends Fi { } 6) class Toon extends Foo, Button { } 7) class Zoom implements Fi, Baz { } 8) interface Vroom extends Fi, Baz { } 9)class Yow extends Foo implements Fi { } 183
  • 184.
    Abstraction In Java Howinterface is different from class ? 1)You can not instantiate an interface. 2)It does not contain any constructors. 3)All methods in an interface are abstract. 4)Interface can not contain instance fields. Interface only contains public static final variables. 5)Interface is can not extended by a class; it is implemented by a class. 6)Interface can extend multiple interfaces. It means interface exhibit the functionality multiple inheritance 184
  • 185.
    Abstraction In Java ImplementingInterfaces in Java A class implementing an interface it means that the class agrees to perform the specific behaviors of the interface. Unless a class is declared as abstract, it should perform all the behaviors of the interface. In order to implement an interface, a class uses the implements keyword. public class Ball implements Bounceable { public void bounce() { } public void setBounceFactor(int bf) { } } 185
  • 186.
    Abstraction In Java Whenwe use abstract and when Interface If we do not know about any things about implementation just we have requirement specification then we should be go for Interface If we are talking about implementation but not completely (partially implemented) then we should be go for abstract Why interface have no constructor ? Because, constructor are used for eliminate the default values by user defined values, but in case of interface all the data members are public static final that means all are constant so no need to eliminate these values. Other reason because constructor is like a method and it is concrete method and interface does not have concrete method it have only abstract methods that's why interface have no constructor. 186
  • 187.
  • 188.
  • 189.
    Abstraction In Java Markeror tagged interface An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation. Example //Way of writing Serializable interface public interface Serializable { } 189
  • 190.
    Abstraction In Java Newfeatures added in interfaces from JDK 8 version 1) Java 8 allows the interfaces to have default and static methods. Why Default methods? Classes such as A, B, C and D implements an interface XYZ Interface. If we add a new method to the XYZ Interface, we have to change the code in all the classes(A, B, C and D) that implements this interface. Here, we have only four classes that implements the interface which we want to change but imagine if there are hundreds of classes implementing an interface then it would be almost impossible to change the code in all those classes. This is why in java 8, we have a new concept “default methods”. These methods can be added to any existing interface and we do not need to implement these methods in the implementation classes mandatorily, thus we can add these default methods to existing interfaces without breaking the code. 190
  • 191.
    Abstraction In Java Whystatic methods? Static methods in interfaces are similar to the default methods except that we cannot override these methods in the classes that implements these interfaces. 191
  • 192.
    Abstraction In Java Interfacewith default method interface MyInterface{ /* This is a default method so we need not * to implement this method in the implementation * classes */ default void newMethod(){ System.out.println("Newly added default method"); } /* Already existing public and abstract method void existingMethod(String str); } 192
  • 193.
    Abstraction In Java Interfacewith static method interface MyInterface{ default void newMethod(){ System.out.println("Newly added default method"); } /* This is a static method. Static method in interface is static void anotherNewMethod(){ System.out.println("Newly added static method"); } //Already existing public and abstract method void existingMethod(String str); } 193
  • 194.
    Abstraction In Java DefaultMethod and Multiple Inheritance The multiple inheritance problem can occur, when we have two interfaces with the default methods of same signature. Lets take an example. interface MyInterface{ default void newMethod(){ System.out.println("Newly added default method"); } void existingMethod(String str); } interface MyInterface2{ default void newMethod(){ System.out.println("Newly added default method"); }void disp(String str); } How to solve this issue? To solve this problem, we can implement this method in the implementation class 194
  • 195.
    Abstraction In Java Java9 has introduced another new feature, Java 9 SE onwards we can have private methods in interfaces. Java 9 introduced private methods in interfaces to remove the redundancy by sharing the common code of multiple default methods through private methods. 195
  • 196.
    Abstraction In Java Multipledefault methods with duplicate code (java8) interface MyInterfaceInJava8 { default void method1() { System.out.println("Starting method"); System.out.println("Doing someting"); System.out.println("This is method1"); } default void method2() { System.out.println("Starting method"); System.out.println("Doing someting"); System.out.println("This is method2"); } } 196
  • 197.
    Abstraction In Java Defaultmethods sharing common code using private methods interface MyInterfaceInJava9 { default void method1() { //calling private method printLines(); System.out.println("This is method1"); } default void method2() { //calling private method printLines(); System.out.println("This is method2"); } private void printLines() { System.out.println("Starting method"); System.out.println("Doing someting"); } } 197
  • 198.
    Abstraction In Java Java9 also allows us to have private static methods in interfaces. Since java 8 we can have static methods in interfaces along with default methods. We can not share the common code of static methods using the non-static private method, we must have to use the private static method to do that. 198
  • 199.
    Abstraction In Java interfaceMyInterfaceInJava9 { static void method1() { printLines(); //calling private method System.out.println("This is method1"); } static void method2() { printLines(); //calling private method System.out.println("This is method2"); } //this must be static else we will get compilation error private static void printLines() { System.out.println("Starting method"); System.out.println("Doing someting"); } default void mymethods() { method1(); method2(); } } 199
  • 200.
    Method Overriding 1) Declaringa method in sub class which is already present in parent class is known as method overriding. 2) Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. 3) In this case the method in parent class is called overridden method and the method in child class is called overriding method. 4) The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code. 200
  • 201.
    Method Overriding Example onmethod overriding class Human{ public void eat(){//Overridden method System.out.println("Human is eating"); } } class Boy extends Human{ public void eat(){//Overriding method System.out.println("Boy is eating"); } } 201
  • 202.
    Method Overriding Rules ofmethod overriding in Java Argument list: The argument list of overriding method (method of child class) must match the Overridden method(the method of parent class). The data types of the arguments and their sequence should exactly match. 202
  • 203.
    Method Overriding Access Modifierof the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the access level of parent class method is public then the overriding method (child class method ) cannot have private, protected and default access level , because all of these three access level are more restrictive than public. class MyBaseClass{ public void disp(){ System.out.println("Parent class method"); }} class MyChildClass extends MyBaseClass{ protected void disp(){//C.E System.out.println("Child class method"); }} 203
  • 204.
    Method Overriding private, staticand final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class. 204
  • 205.
  • 206.
    Association In Java 1)Association is relation between two separate classes which establishes through their Objects. 2) Association can be one-to-one, one-to-many, many- to-one, many-to-many. 3) In Object-Oriented programming, an object communicates to other object to use functionality and services provided by that object. 4) Composition and Aggregation are the two forms of association. 206
  • 207.
    Association In Java Aggregationor HAS-A relationship between two classes. When class A has a reference to the object of another class B, class A is said to be in a HAS-A relationship with class B. Through this reference of class B in it, class A can call and use the needed features of class B, without copying all the unnecessary code of class B in it. Let's take an example class Student{ String name; Address ad; } Here in the above code, you can say that Student has-a Address. 207
  • 208.
    Association In Java Compositionor IS-A relationship between two classes An IS-A signifies a relationship between the two classes that are connected to each other through inheritance. The basis of an IS-A relationship is - a)When a class extends another concrete(non-abstract) class. b)When a class extends an abstract class. c)When a class implements an interface. 208
  • 209.
  • 210.
    String Handling InJava Introduction 1)Basically, string is a sequence of characters but it’s not a primitive type. 2)In Java, CharSequence Interface is used for representing a sequence of characters. 3)CharSequence interface is implemented by String, StringBuffer and StringBuilder classes. These three classes can be used for creating strings in java. 4)When we create a string in java, it actually creates an object of above three classes 210
  • 211.
  • 212.
    String Handling InJava Creation of strings 1) Using string literal While creating String object using string literal, new operator is not used. String objects can be created using string literal as shown below: Example String str1 = “James”; 212
  • 213.
  • 214.
    String Handlin InJava What is String Constant Pool? The String Constant Pool (SCP) is a place where objects with string literals are stored. It is a part of the heap memory area. 214
  • 215.
  • 216.
    String Handling InJava 216 When we create a String using double quotes, JVM looks in the String pool(refers to collection of Strings which are stored in heap memory) to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
  • 217.
    String Handling InJava 217 In the above image, two Strings are created using literal i.e “Apple” and “Mango”. Now, when third String is created with the value “Apple”, instead of creating a new object, the already present object reference is returned.
  • 218.
    String Handling InJava 2) Using new keyword When String object is created using the new keyword, two same string objects are created. One in heap area (outside SCP) & another inside String Constant Pool (SCP). Example String str1 = new String(“James”); 218
  • 219.
    String Handling InJava Difference between String literal and New String object When you use new String( "Hello" ), it explicitly creates a new and referentially distinct instance of a String object. It is an individual instance of the java.lang.String class. 219
  • 220.
    String Handling InJava String s=“Harry"; may reuse an instance from the string constant pool if one is available (String Pool is a pool of Strings stored in Java heap memory ) otherwise create a new instance 220
  • 221.
    String Handling InJava Strings Are Immutable Objects The objects in which you cannot change anything once the object is created are known as Immutable objects. Once a String object is created, it can never be changed so it is an immutable object but its reference variable is not. 221
  • 222.
    String Handling InJava String samplestring="Machine Learning"; samplestring.concat("Masters"); System.out.println(samplestring); Variable samplestring, which stores the string “Machine Learning“. Now, if you concatenate this string with another string “Masters“, then the object created for “Machine Learning” will not change. Instead, a new object will be created for “Machine Learning Masters“. 222
  • 223.
    String Handling InJava String Class Methods public char charAt(int index) Returns the character at the specified index. Specified index value should be between '0' to 'length() -1' both inclusive. It throws IndexOutOfBoundsException if index is invalid/ out of range. String name = "James Smith"; char ch1 = name.charAt(3) char ch2 = name.charAt(6); char ch3 = name.charAt(9); 223
  • 224.
  • 225.
    String Handling InJava public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) This method is used to copy set of characters of the invoking string into the specified character array. Parameters srcBegin − index of the first character in the string to copy. srcEnd − index after the last character in the string to copy. dst − the destination array. dstBegin − the start offset in the destination array. String s = "Its Beyond Simple"; int start = 4; int end = 10; char storage[] = new char[end-start]; s.getChars(start,end,storage,0); System.out.println(storage); 225
  • 226.
  • 227.
    String Handling InJava public byte[] getBytes() This method encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. String Str1 = new String("Welcome to NareshIt"); byte[]b=Str1.getBytes();//byte array having all charactes with ascii values 227
  • 228.
    String Handling InJava public char[] toCharArray() This method converts this string to a new character array. It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string. String str = new String("Welcome to Nacre"); char[]ch=str.toCharArray();//array contains the all characters of the string 228
  • 229.
    String Handling InJava boolean equals(Object anObject) Used to compare two strings. It returns true if both string represents same sequence of characters else false. String s1="hello"; String s2="welcome"; s1.equals(s2);// returns false s1.equals("hello");// returns true. 229
  • 230.
    String Handling InJava boolean equalsIgnoreCase(String anotherString) Used to compare two strings, ignoring the case(upper or lower case). It returns true if both the string are of same length and represents same sequence of character ignoring the case else returns false. String s1="hello"; s1.equalsIgnoreCase("Hello");// returns true 230
  • 231.
    String Handling InJava regionMatches() method This method tests if the two Strings are equal. Using this method we can compare the substring of input String with the substring of specified String. public boolean regionMatches(int toffset, String other, int ooffset, int len) Case sensitive test. public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) It has option to consider or ignore the case. 231
  • 232.
    String Handling InJava String str1 = new String("Hello, How are you"); String str2 = new String("How"); String str3 = new String("HOW"); System.out.println(str1.regionMatches(7, str2, 0, 3)); System.out.println(str1.regionMatches(7, str3, 0, 3)); System.out.println(str1.regionMatches(true, 7, str3, 0, 3)); 232
  • 233.
    String Handling InJava boolean startsWith(String prefix) checks if a string starts with the string represented by prefix. String s1=“refresh java”; s1.startsWith("refresh");// returns true. s1.startsWith("Refresh");// returns false. 233
  • 234.
    String Handling InJava public boolean endsWith(String suffix) This method checks whether the String ends with a specified suffix. This method returns a boolean value true or false. If the specified suffix is found at the end of the string then it returns true else it returns false. String str1 = new String("This is a test String"); boolean var1 = str1.endsWith("String"); System.out.println("str1 ends with String: "+ var1); 234
  • 235.
    String Handling InJava int compareTo(String str) The Java String compareTo() method is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative. String str1 = "String method tutorial"; String str2 = "compareTo method example"; int var1 = str1.compareTo( str2 ); System.out.println("str1 & str2 comparison: "+var1); 235
  • 236.
    String Handling InJava substring() method This method is used to get the substring of a given string based on the passed indexes. There are two variants of this method. 1. When we pass only the starting index: public String substring(int beginIndex) Returns the substring starting from the specified index i.e beginIndex and extends to the character present at the end of the string. For example – "Hello".substring(1) would return "ello". 2. When we pass both the indexes, starting index and end index: public String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1. Thus the length of the substring is endIndex-beginIndex. In other words you can say that beginIndex is inclusive and endIndex is exclusive while getting the substring. For example – "Chaitanya".substring(2,5) would return "ait". 236
  • 237.
    String Handling InJava The concat() method public String concat(String str) This method concatenates the string str at the end of the current string. For example – s1.concat("Hello"); would concatenate the String “Hello” at the end of the String s1. This method can be called multiple times in a single statement like this String s1="Nacre"; s1= s1.concat("Software").concat("Service").concat("Pvt.Ltd"); 237
  • 238.
    String Handling InJava replace() method String replace(char oldChar, char newChar) It replaces all the occurrences of a oldChar character with newChar character. For example, "pog pance".replace('p', 'd') would return dog dance. 238
  • 239.
    String Handling InJava replaceFirst() method String replaceFirst(String regex, String replacement) It replaces the first substring that fits the specified regular expression with the replacement String. PatternSyntaxException if the specified regular expression(regex) is not valid. String str = new String("facebook.com"); System.out.println(str.replaceFirst("com", "net")); Result is facebook.net 239
  • 240.
    String Handling InJava replaceAll() method String replaceAll(String regex, String replacement) It replaces all the substrings that fits the given regular expression with the replacement String. String str = new String("My .com site is facebook.com"); System.out.println(str.replaceAll("com", "net")); Output is My.net site is facebook.net 240
  • 241.
    String Handling InJava indexOf()method This method is used to find the index of a specified character or a substring in a given String. There are 4 variations of this method in String class 1)int indexOf(int ch) It returns the index of the first occurrence of character ch in a given String. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Index of J :: "+s.indexOf('J')); 2)int indexOf(int ch, int fromIndex) It returns the index of first occurrence of character ch in the given string after the specified index “fromIndex”. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Index of J from 8th index :: "+s.indexOf('J',8)); 241
  • 242.
  • 243.
    String Handling InJava 3)int indexOf(String str) Returns the index of string str in a particular String. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Index of JAVA :: "+s.indexOf("JAVA")); 4)int indexOf(String str, int fromIndex) Returns the index of string str in the given string after the specified index “fromIndex”. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Index of LIKE from 4th index :: "+s.indexOf("LIKE",4)); Note All the above variations returns -1 if the specified char/substring is not found in the particular String. 243
  • 244.
  • 245.
    String Handling InJava lastIndexOf()method This method is used to find out the index of last occurrence of a character or a substring in a given String. To find out the last occurrence of the specified character or a string, this method starts the search from the end of string and proceeds backwards from there. If the fromIndex is specified during the method call, then the backward search begins from the specified index fromIndex 245
  • 246.
    String Handling InJava 1)int lastIndexOf(int ch) It returns the last occurrence of character ch in the given String. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Last Index of J :: "+s.lastIndexOf('J')); 2)int lastIndexOf(int ch, int fromIndex) It returns the last occurrence of ch, it starts looking backwards from the specified index “fromIndex”. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Last Index of J from 16th index :: "+s.lastIndexOf('J',16)); 3)int lastIndexOf(String str) Returns the last occurrence of substring str in a String. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Last Index of LIKE :: "+s.lastIndexOf("LIKE")) 4)int lastIndexOf(String str, int fromIndex) Returns the last occurrence of str, starts searching backward from the specified index “fromIndex”. String s = "I LIKE JAVA LIKE JAVA"; System.out.println("Last Index of LIKE from 9th index :: "+s.lastIndexOf("LIKE",9)); 246
  • 247.
  • 248.
    String Handling InJava contains() method This method checks whether a particular sequence of characters is part of a given string or not. This method returns true if a specified sequence of characters is present in a given string, otherwise it returns false. Syntax of contains() method public boolean contains(CharSequence str) If the CharSequence is null then this method throws NullPointerException. 248
  • 249.
    String Handling InJava intern() method 1)It is used for getting the string from the memory if it is already present. 2)This method ensures that all the same strings share the same memory. 3)This method searches the memory pool for the mentioned String, if the string is found then it returns the reference of it, else it allocates a new memory space for the string and assign a reference to it. 4)For example, creating a string “hello” 10 times using intern() method would ensure that there will be only one instance of “Hello” in the memory and all the 10 references point to the same instance. 249
  • 250.
    String Handling InJava //String object in heap String str1 = new String("hello world"); //String literal in pool String str2 = "hello world"; //String literal in pool String str3 = "hello world"; //String object interned to literal //It will refer to existing string literal String str4 = str1.intern(); 250
  • 251.
    String Handling InJava isEmpty()method This method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. In other words you can say that this method returns true if the length of the string is 0. public boolean isEmpty() 251
  • 252.
    String Handling InJava join() method In Java 8 we have a new Method join() in the Java String class. Java String join() method concatenates the given Strings and returns the concatenated String. public static String join(CharSequence delimiter, CharSequence... elements) The first argument of this method specifies the delimiter that is used to join multiple strings. String message = String.join("-", "This", "is", "a", "String"); Output is: "This-is-a-String" 252
  • 253.
    String Handling InJava split() method This method used for splitting a String into its substrings based on the given delimiter or regular expression. We have two variants of split() method in String class. 1. String[] split(String regex): It returns an array of strings after splitting an input String based on the delimiting regular expression. 2. String[] split(String regex, int limit): This Java String split method is used when we want the substrings to be limited. The only difference between this method and above method is that it limits the number of strings returned after split up. For e.g. split("anydelimiter", 3) would return the array of only 3 strings even if the delimiter is present in the string more than 3 times. 253
  • 254.
    String Handling InJava String str = new String("28/12/2013"); String array1[]= str.split("/"); for (String temp: array1){ System.out.println(temp); } String array2[]= str.split("/", 2); for (String temp: array2){ System.out.println(temp); } 254
  • 255.
    String Handling InJava Difference between zero and negative limit in java string split method Limit zero excludes trailing empty strings, where as negative limit includes trailing strings String s="bbaaccaa"; String arr1[]= s.split("a", -1); String arr2[]= s.split("a", 0); 255
  • 256.
    String Handling InJava Java String split with multiple delimiters (special characters) String s = " ,ab;gh,bc;pq#kk$bb"; String[] str = s.split("[,;#$]"); Word as a regular expression in Java String split method String str = "helloxyzhixyzbye"; String[] arr = str.split("xyz"); Splitting string based on whitespace String str = "My name is Ram"; String[] arr = str.split(" "); for (String s : arr) System.out.println(s); 256
  • 257.
    String Handling InJava format() method This method is used for formatting the String. There are so many things you can do with this method, for example you can concatenate the strings using this method and at the same time, you can format the output of concatenated string. public static String format(Locale l,String format, Object... args) Returns a formatted string using the specified locale, format string, and arguments. public static String format(String format, Object... args) Returns a formatted string using the specified format string and arguments. 257
  • 258.
    String Handling InJava Java String Format Specifiers %c – Character %d – Integer %s – String %o – Octal %x – Hexadecimal %f – Floating number %h – hash code of a value 258
  • 259.
    String Handling InJava String str = "just a string"; //concatenating string using format String formattedString = String.format("My String is %s", str); // %.6f is for having 6 digits in the fractional part String formattedString2 = String.format("My String is %.6f",12.121); 259
  • 260.
    String Handling InJava We can specify the argument positions using %1$, %2$,..format specifiers. Here %1$ represents first argument, %2$ second argument and so on. String str1 = "cool string"; String str2 = "88"; String fstr = String.format("My String is: %1$s, %1$s and %2$s", str1, str2); System.out.println(fstr); Result is: My String is: cool string, cool string and 88 260
  • 261.
    String Handling InJava Left padding an integer number with 0's and converting it into a String using Java String format() method. int str = 88; String formattedString = String.format("%05d", str); System.out.println(formattedString);// 00088 261
  • 262.
    String Handling InJava Displaying String, int, hexadecimal, float, char, octal value using format() method String str1 = String.format("%d", 15); // Integer value String str2 = String.format("%s", "BeginnersBook.com"); // String String str3 = String.format("%f", 16.10); // Float value String str4 = String.format("%x", 189); // Hexadecimal value String str5 = String.format("%c", 'P'); // Char value String str6 = String.format("%o", 189); // Octal value 262
  • 263.
    String Handling InJava StringBuffer Class 1)As we know that String objects are immutable, so if we do a lot of modifications to String objects, we may end up with a memory leak. To overcome this we use StringBuffer class. 2)Java StringBuffer class is used to create mutable (modifiable) string object. 3)StringBuffer class represents growable and writable character sequence. It is also thread-safe i.e. multiple threads cannot access it simultaneously. 4)Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger. 263
  • 264.
    String Handling InJava Constructors of StringBuffer class 1)StringBuffer ( ) : Creates an empty string buffer with the initial capacity of 16. 2)StringBuffer ( int capacity ) : Creates an empty string buffer with the specified capacity as length. 3)StringBuffer ( String str ) : Creates a string buffer initialized to the contents of the specified string. 4)StringBuffer ( charSequence[] ch ) : Creates a string buffer that contains the same characters as the specified CharSequence. 264
  • 265.
    String Handling InJava Important methods of StringBuffer class append() method The append() method concatenates the given argument(string representation) to the end of the invoking StringBuffer object. StringBuffer class has several overloaded append() method. StringBuffer append(String str) StringBuffer append(int n) StringBuffer append(Object obj) StringBuffer strBuffer = new StringBuffer("Core"); strBuffer.append("JavaGuru"); System.out.println(strBuffer); strBuffer.append(101); System.out.println(strBuffer); 265
  • 266.
    String Handling InJava insert() method The insert() method inserts the given argument(string representation) into the invoking StringBuffer object at the given position. StringBuffer strBuffer=new StringBuffer("Core"); strBuffer.insert(1,"Java"); System.out.println(strBuffer); 266
  • 267.
    String Handling InJava replace() method The replace() method replaces the string from specified start index to the end index. StringBuffer strBuffer=new StringBuffer("Core"); strBuffer.replace( 2, 4, "Java"); System.out.println(strBuffer); 267
  • 268.
    String Handling InJava reverse() method This method reverses the characters within a StringBuffer object. StringBuffer strBuffer=new StringBuffer("Core"); strBuffer.reverse(); System.out.println(strBuffer); 268
  • 269.
    String Handling InJava delete() method The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex. StringBuffer strBuffer=new StringBuffer("Core"); strBuffer.delete( 2, 4); System.out.println(strBuffer); 269
  • 270.
    String Handling InJava capacity() method The capacity() method returns the current capacity of StringBuffer object. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur. StringBuffer strBuffer=new StringBuffer(); System.out.println(strBuffer.capacity()); strBuffer.append("1234"); System.out.println(strBuffer.capacity()); strBuffer.append("123456789112"); System.out.println(strBuffer.capacity()); strBuffer.append("1"); System.out.println(strBuffer.capacity()); //(oldcapacity*2)+2 270
  • 271.
  • 272.
    String Handling InJava StringBuilder Class 1)StringBuilder objects are like String objects, except that they can be modified. Hence Java StringBuilder class is also used to create mutable (modifiable) string object. 2)StringBuilder is same as StringBuffer except for one important difference. StringBuilder is not synchronized, which means it is not thread safe. 3)This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread. 4)Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used. 272
  • 273.
    String Handling InJava Constructors of StringBuilder class StringBuilder ( ) : Constructs a string builder with no characters in it and an initial capacity of 16 characters. StringBuilder ( int capacity ) : Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. StringBuilder ( String str ) : Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is 16 plus the length of the string argument. 273
  • 274.
  • 275.
  • 276.
  • 277.
    Exception Handling InJava What is an Error? Errors are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Some Errors in Java are VirtualMachineError, OutOfMemoryError, etc. Consider a situation, when a program attempts to allocate memory from the JVM but there is not enough space to satisfy the user request. Or, when a program tries to load a class file by calling Class.forName() method and the class file is corrupt. Such exceptions are known as an error. 277
  • 278.
    Exception Handling InJava What is an Exception? An Exception is an unexpected event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. Some common examples of Exceptions in Java are 1)Divide by zero errors 2)Trying to access the array elements with an invalid index 3)Invalid input data by the user 278
  • 279.
    Exception Handling InJava Difference between error and exception 279 Error Exception 1. Impossible to recover from an error 1. Possible to recover from exceptions 2. Errors are of type ‘unchecked’ 2. Exceptions can be either ‘checked’ or ‘unchecked’ 3. Occur at runtime 3. Can occur at compile time or run time 4. Caused by the application running environment 4. Caused by the application itself
  • 280.
    Exception Handling InJava What is an Exception Handling? What happen when Exception is raised? To design the program in such a way that even if there is an exception, all operations are performed then only the program should be terminated is called exception handling Whenever an exception occurs while executing a statement, creates an exception object(contains a line number where the exception occurred, type of exception ) and then the normal flow of the program halts and JRE tries to find someone that can handle the raised exception. Exception Handler is the block of code that can process the exception object. 280
  • 281.
  • 282.
    Exception Handling InJava Exception Hierarchy In Java all exceptions are represented as an object of classes .All these classes are subclass of Exception. Throwable is the superclass has two subclasses Exception and Error. The Exception class, and its subclasses, is used to represent exceptional situations in a Java program that may be handled appropriately. The Error class and its subclasses, represent abnormal conditions that are caused by the application running environment. 282
  • 283.
  • 284.
    Exception Handling InJava Types of Exceptions There are two types of exceptions in Java: 1)Checked exceptions 2)Unchecked exceptions Checked Exceptions A checked exception is a compile-time exception, that is, a Java compiler checks or notifies during the compilation-time. The programmer cannot simply ignore these exceptions and should take care to handle these exceptions. If the programmer does not write the code to handle them then there will be a compilation error. A checked exception extends the Exception class. Some checked Exceptions are SQLException, IOException, ClassNotFoundException, InvocationTargetException, etc. 284
  • 285.
    Exception Handling InJava Unchecked Exceptions An exception that occurs during the execution of a program is called an unchecked or a runtime exception. So the compiler does not check whether the programmer has written the code to handle them or not but it is the responsibility of the programmer to handle the unchecked exceptions and provide a safe exit. For example, if a program attempts to divide a number by zero. Or, when there is an illegal arithmetic operation, this impossible event generates a runtime exception. Some unchecked exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, InputMismatchException, IllegalStateException, etc. 285
  • 286.
    Exception Handling InJava In Java, exception handling is done using five keywords, 1)try 2)catch 3)throw 4)throws 5)finally Exception handling is done by transferring the execution of a program to an appropriate exception handler when exception occurs. 286
  • 287.
    Exception Handling InJava try block 1)The try is used to define a block of code in which exceptions may occur, it must be used within the method. 2)Java try block must be followed by either catch or finally block. No intermediate statements are allowed between try and catch block or between try and finally 3)If any exception occurs in try block then CPU control comes out to the try block and executes appropriate catch block. 4)After executing appropriate catch block, CPU control never goes to try block to execute the rest of the statements. 287
  • 288.
    Exception Handling InJava try{ } //invalid try{ } int x; catch(Exception e){ e.printStackTrace(); } //invalid try{ } int y; finally{ } //invalid try{ } catch(Exception e){ e.printStackTrace(); } //valid try{ } finally{ } //valid 288
  • 289.
    Exception Handling InJava catch block 1)If an exception occurs within the try block, it is thrown. The catch block code catches this exception and handle it in some rational manner 2)It must be used after the try block only, you can use multiple catch block with a single try. 3)Catch block will execute exception occurs in try block. 4)You can write multiple catch blocks for handling multiple exceptions to make your application strong. 5)At a time only one catch block will execute out of multiple catch blocks. 6)In catch block you declare an object of Exception/ sub class of an Exception and it will be internally referenced by JVM. 289
  • 290.
  • 291.
    Exception Handling InJava finally block 1)Java finally block is a block that is used to execute important code such as closing connection, stream etc. 2)In normal case when there is no exception in try block then the finally block is executed after try block. However if an exception occurs then the catch block is executed before finally block. 3)The statements present in the finally block execute even if the try block contains control transfer statements like return, break or continue. 4)If an exception is thrown, finally runs. If an exception is not thrown, finally runs. 5)If the exception is caught, finally runs.If the exception is not caught, finally runs 291
  • 292.
  • 293.
  • 294.
    Exception Handling InJava Note 1)It is illegal to use a try clause without either a catch clause or a finally clause. 2) Any catch clauses must immediately follow the try block. Any finally clause must immediately follow the last catch clause (or it must immediately follow the try block if there is no catch). 3) It is legal to omit either the catch clause or the finally clause, but not both. 294
  • 295.
    Exception Handling InJava try-with resources Generally, when we use any resources like streams, connections, etc. we have to close them explicitly using finally block. In the following program, we are reading data from a file using FileReader and we are closing it using finally block. try-with-resources, also referred as automatic resource management, is a new exception handling mechanism that was introduced in Java 7, which automatically closes the resources used within the try catch block 295
  • 296.
    Exception Handling InJava try(FileReader fr = new FileReader("file path")) { // use the resource } catch () { // body of catch } } 296
  • 297.
    Exception Handling InJava try with out resource management FileReader fr = null; try { File file = new File("file.txt"); fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); }finally { try { fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } 297
  • 298.
    Exception Handling InJava try with resource management try(FileReader fr = new FileReader("E://file.txt")) { char [] a = new char[50]; fr.read(a); // reads the contentto the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); } 298
  • 299.
    Exception Handling InJava Multiple catch blocks 1) More than one exception could be raised by a single piece of code, to handle such a situation, two or more catch clauses are specified, each catching a different type of exception. 2) Exception subclasses if any must come before any of their super classes. Otherwise, the subclass would never be reached 299
  • 300.
    Exception Handling InJava try { int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e){ System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } catch(Exception e) { System.out.println(e); } 300
  • 301.
    Exception Handling InJava Note While using multiple catch statements, it is important to remember that sub classes of class Exception inside catch must come before any of their super classes otherwise it will lead to compile time error. This is because in Java, if any code is unreachable, then it gives compile time error. 301
  • 302.
    Exception Handling InJava try { int arr[]={1,2}; arr[2]=3/0; } catch(Exception e) { //This block handles all Exception System.out.println("Generic exception"); } catch(ArrayIndexOutOfBoundsException e) { //This block is unreachable System.out.println("array index out of bound exception"); } 302
  • 303.
    Exception Handling InJava Before Java 7, we had to write multiple exception handling codes for different types of exceptions even if there was code redundancy. try { int array[] = new int[10]; array[10] = 30 / 0; } catch (ArithmeticException e) { System.out.println(e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } 303
  • 304.
    Exception Handling InJava In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe |. Its syntax is: try { // code } catch (ExceptionType1 | Exceptiontype2 ex) { // catch block } Example try { int array[] = new int[10]; array[10] = 30 / 0; } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } 304
  • 305.
    Exception Handling InJava If the base exception class has already been specified in the catch block, do not use child exception classes in the same catch block. Otherwise, we will get a compilation error. Example try { int array[] = new int[10]; array[10] = 30 / 0; } catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } 305
  • 306.
    Exception Handling InJava throws clause We have a method myMethod() that has statements may generate either ArithmeticException or NullPointerException, to handle that use try-catch as shown below: public void myMethod(){ try { // Statements that might throw an exception } catch (ArithmeticException e) { // Exception handling statements } catch (NullPointerException e) { // Exception handling statements } suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable. 306
  • 307.
    Exception Handling InJava Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword. Syntax type method_name(parameter_list) throws exception_list { // definition of method } 307
  • 308.
    Exception Handling InJava throw clause 1)It is used for throw an exception explicitly and catch it. 2)It is used in software testing to test whether a program is handling all the exceptions as claimed by the programmer 3)throw clause can be used to throw our own exceptions 308
  • 309.
    Exception Handling InJava Explicitly handling the exception static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } 309
  • 310.
    Exception Handling InJava User defined exceptions/Custom exceptions Rules to design user defined Exception 1)Create a package with valid user defined name. 2)Create any user defined class. 3)Make that user defined class as derived class of Exception or RuntimeException class. 4)Declare parametrized constructor with string variable. 5)call super class constructor by passing string variable within the derived class constructor. 6)Save the program with public class name.java 310
  • 311.
  • 312.
    Exception Handling InJava Rethrowing an exception There might be situations in your program where you want to both catch an exception in your code and also want its caller be notified about the exception. This is possible by rethrowing the exception using throw statement. 312
  • 313.
    Exception Handling InJava Calling method Caller method pubic void divide() { int x,y,z; try { x = 6 ; y = 0 ; z = x/y ; System.out.println(x + "/"+ y +" = " + z); } catch(ArithmeticException e) { System.out.println("Exception Caught in Divide()"); System.out.println("Cannot Divide by Zero in Integer Division"); throw e; // Rethrows an exception } } public static void main(String[] args) { System.out.println("Start of main()"); try { divide(); } catch(ArithmeticException e) { System.out.println("Rethrown Exception Caught in Main()"); System.out.println(e); } } 313
  • 314.
    Exception Handling InJava Nested try catch block in Java When a try catch block is present in another try block then it is called the nested try catch block. Nested try blocks are useful when different statements of try block throw different types of exceptions. If the exception thrown by the inner try block can not be caught by it’s catch block, then this exception is propagated to outer try blocks. Any one of the outer catch block should handle this exception otherwise program will terminate abruptly. 314
  • 315.
    Exception Handling InJava try { //Outer try block //Some Statements try { //Inner try block //Some Statements } catch (Exception ex) { //Inner catch block } } catch(Exception ex) { //Outer catch block } 315
  • 316.
    Exception Handling InJava String[] s = {"abc", "123", null, "xyz"}; //String array containing one null object for (int i = 0; i < s.length; i++){ try { //Outer try block int a = s[i].length(); //may throw NullPointerException try { //Inner try block a = Integer.parseInt(s[i]); //may throw NumberFormatException } catch (NumberFormatException ex){ //Inner catch block System.out.println("NumberFormatException will be caught here"); } } catch(NullPointerException ex){ //Outer catch block System.out.println("NullPointerException will be caught here"); } 316
  • 317.
    Exception Handling InJava Exception Propagation Considering a scenario, in which your program starts its execution at the main() method, main() calls method1(), method1() calls method2(), method2() calls method3(), now the call stack should look like the figure below-: 317
  • 318.
    Exception Handling InJava The currently executing method is at the top of the call stack, which in this example is method3(). Let's say while executing method3(), an exception is raised/thrown. Now this exception is thrown down to the next method in the call stack, i.e. method2(), which in turn throws the exception down to next method in the call stack, i.e. method1(). The process continues until the exception is thrown to the method at the bottom of the call stack, i.e. main() method. This process is called exception propagation 318
  • 319.
    Exception Handling InJava class Exp{ public static void main(String... ar){ Exp ob = new Exp(); ob.method1(); } public void method1(){ method2(); } public void method2(){ method3(); } public void method3(){ System.out.println(100/0); //ArithmeticException is raised/thrown by the program. System.out.println("Hello"); //This statement will not be executed. } } 319
  • 320.
  • 321.
    Student Party When studentsget together for a party, they like to have beers. A student party is successful when the number of beers is between 40 and 60 inclusive. If it is the weekend there is no upper bound on the number of beers. Return true if the party with the given values is successful, or false otherwise. Print ‘Party Is Successful’ when return true otherwise print ‘Party Is Failure’. public Boolean party(int beers, Boolean isWeekend) { } 321
  • 322.
  • 323.
  • 324.
  • 325.
  • 326.
    Multithreading In Java ProcessVs Thread An executing program is called a process. Each process can have a single thread or multiple threads. So that the thread is the smallest unit of a process that can run concurrently with the other parts (other threads) of the same process. 326
  • 327.
    Multithreading In Java ProcessThread An executing program is called a process. A thread is a small part of a process. Every process has its separate address space. All the threads of a process share the same address space of a process. Process-based multitasking allows a computer to run two or more than two programs concurrently. Thread-based multitasking allows a single program to run two or more threads concurrently. Communication between two processes is expensive and limited. Communication between two threads is less expensive as compared to process. Context switching from one process to another process is expensive. Context switching from one thread to another thread is less expensive as compared to process. A process has its own address space, global variables, signal handlers, open files, child processes, accounting information. A thread has its own register, state, stack, program counter. 327
  • 328.
    Multithreading In Java Multitasking Multitaskingis when a single CPU performs several tasks at the same time. To perform multitasking, the CPU switches among theses tasks very frequently so that user can interact with each program simultaneously. 328
  • 329.
    Multithreading In Java Multithreading Aprocess can have multiple threads simultaneously, and the CPU switches among these threads so frequently making an impression on the user that all threads are running simultaneously and this is called multithreading 329
  • 330.
    Multithreading In Java MultitaskingMultithreading In multitasking, the system allows executing multiple programs and tasks at the same time In multithreading, the system executes multiple threads of the same or different processes at the same time. In multitasking, CPU has to switch between multiple programs so that it appears that multiple programs are running simultaneously. In multithreading CPU has to switch between multiple threads to make it appear that all threads are running simultaneously. Multitasking allocates separate memory and resources for each process/program In multithreading threads belonging to the same process shares the same memory and resources as that of the process.330
  • 331.
    Multithreading In Java Achievemultithreading in java In java language multithreading can be achieve in two different ways. 1)Using Thread class 2)Using Runnable interface 331
  • 332.
    Multithreading In Java UsingThread Class 1)Create any user defined class and make that one as a derived class of Thread class. class MyThread extends Thread{ } 2)Override run() method of Thread class (It contains the logic of perform any operation) 3)Create an object for user-defined thread class and attached that object to predefined thread class object. MyThread obj=new MyThread(); Thread t=new Thread(obj); 4)Call start() method of thread class to execute the thread t.start(); 332
  • 333.
  • 334.
    Multithreading In Java UsingRunnable Interface 1)Define the class that implements the Runnable interface and implement the run () method of the Runnable interface in the class. 2)Create an instance of the defined class. 3)Create an instance of the Thread class using the Thread (Runnable target) constructor. 4)Start the thread by invoking the start () method on your Thread object. 334
  • 335.
    Multithreading In Java Whydon’t we call run() method directly, why call start() method? 1) When you directly call the run() method then the code inside run() method is executed in the same thread which calls the run method. JVM will not create a new thread until you call the start method. 2) On the other hand, when you call the Thread.start() method, then the code inside run() method will be executed on a new thread, which is actually created by the start() method. 3) You can call the run method multiple time, JVM will not throw any error but when you cannot call the start() method on same thread instance. 4) The first time, t.start() will create a new thread but the second time it will throw java.lang.IllegalStateException, because the thread is already started and you cannot restart it again, you can only pause a thread in Java. 335
  • 336.
    Multithreading In Java Directlycalling the run() method 336 public void run(){ for(int i=1;i<=3;i++){ try{ Thread.sleep(1000); } catch(InterruptedException ie){ ie.printStackTrace(); } System.out.println(i); } } public static void main(String args[]){ Thread th1 = new Thread(new RunMethodExample(), "th1"); Thread th2 = new Thread(new RunMethodExample(), "th2"); th1.run(); th2.run(); }
  • 337.
    Multithreading In Java Executethe thread by using start()method 337 public void run(){ for(int i=1;i<=3;i++){ try{ Thread.sleep(1000); } catch(InterruptedException ie){ ie.printStackTrace(); } System.out.println(i); } public static void main(String args[]){ Thread th1 = new Thread(new RunMethodExample(), "th1"); Thread th2 = new Thread(new RunMethodExample(), "th2"); th1.start(); th2.start(); }
  • 338.
    Multithreading In Java Differencebetween Thread and Runnable 338 Thread Class Runnable Interface Each thread creates a unique object and gets associated with it so more memory required. Multiple threads share the same objects. So less memory is used. In Java, multiple inheritance not allowed hence, after a class extends Thread class, it can not extend any other class. If a class define thread implementing the Runnable interface it has a chance of extending one class. A user must extend thread class only if it wants to override the other methods in Thread class. If you only want to specialize run method then implementing Runnable is a better option. Extending Thread class introduces tight coupling as the class contains code of Thread class and also the job assigned to the thread Implementing Runnable interface introduces loose coupling as the code of Thread is separate form the job of Threads.
  • 339.
    Multithreading In Java ThreadLife Cycle The various states of java thread 1) New 2) Runnable 3) Running 4) Waiting 5) Timed Waiting 6) Blocked 7) Terminated 339
  • 340.
  • 341.
    Multithreading In Java NewState 1)Whenever we create an instance of Thread, Thread gets a state called “ New ” state. 2)In this case, Thread is just created but not started, in other words we have a thread object but there is no thread execution. Thread t1 = new Thread (); 341
  • 342.
    Multithreading In Java RunnableState 1)Whenever we start the thread it moves from “ New ” state to “ Runnable ” state. 2)In this case, thread is ready to be executed but it’s just waiting for the Thread scheduler to pick it for execution. 3)In this state, a new call stack will be created for the thread. 4)Below line takes the thread from “ New ” state to “ Runnable ” state. t.start(); 342
  • 343.
    Multithreading In Java RunningState 1) This is not the standard thread state defined by Java but its used to indicate that the thread is currently running or executing the logic. 2) Moving thread from “ Runnable ” state to “ Running ” state is entirely dependent on Thread scheduler. Thread scheduler is the one which decides whether to move the thread from “ Runnable ” state to “ Running ” state or put it on hold in “ Runnable ” state by giving chance to other Runnable threads. 3) Thread scheduler is operating system dependent most of the operating systems follow Round-robin scheduling. In this case, each thread is given a fixed amount of processor time called as “ quantum ” or “ time slice ” within which it has to execute. 4) Any thread which has got this time slice to execute its task is said to be in “ Running ” state. 5) Once time slice expires, thread will be returned to “ Runnable ” state and another thread will be assigned to the processor. 6) This process that operating system uses to determine which thread has to go from “ Runnable ” state to “ Running ” state is called “ Thread scheduling ” 343
  • 344.
    Multithreading In Java WaitingState 1)In this case,Thread will be moved from “ Running ” state to “ Waiting ” state by calling its wait() method. 2)This can be done whenever we want currently running thread to wait for some other thread to execute and notify back to it to continue the execution. 3)Once the thread wait is notified , then the waited thread will be moved to “ Runnable ” state. 344
  • 345.
    Multithreading In Java Timedwaiting state 1)In this case, Thread will be moved from “ Running ” state to “ Waiting ” state with specified waiting time. 2)This can be done whenever we want currently running thread to wait for some specified amount of time. 3)Once the specified amount of time is completed, then the waited thread will be moved to “ Runnable ” state. 4)We can put the thread to “ Timed waiting ” by calling sleep(long millis) or wait(long millis) method 345
  • 346.
    Multithreading In Java BlockedState 1)In this case, thread will be moved from “ Running ” state to “ Blocked ” state. 2)This can happen due to various reasons like 1) Current thread might try to read data from IO stream but there is not data to read. 2) Thread might be waiting to acquire the lock to enter synchronized block. 3)Thread will be moved from "Blocked" state to “ Runnable ” state once the data on the stream is available or lock is released by other thread. 346
  • 347.
    Multithreading In Java TerminatedState 1)Thread will be moved to Terminated state(also called Dead state) when it completes its execution successfully. 2)It can also be terminated forcefully by killing it. 347
  • 348.
    Multithreading In Java Terminatingthe Thread A thread will terminate automatically when it comes out of run() method. To terminate the thread on our own the following steps can be used 1) Create a boolean type variable and initialize it to false boolean stop=false; 2) Let us assume that we want to terminate the thread when the user press<Enter>key. So, when the user press that button, make the boolean type variable as true stop=true; 3) Check this variable in run()method and when it is true, make the thread return from the run() method. public void run(){ if(stop==true)return; } 348
  • 349.
    Multithreading In Java SingleTasking Using a Thread 1)A thread can be employed to execute one task at a time. Suppose there are 3 tasks to be executed. We can create a single thread and pass these 3 tasks one by one to the thread is called as single tasking using a thread. 2)For this purpose, we can write all these tasks separately in separate methods: task1(), task2(),task3(). 3)Then these methods should be called from run() method, one by one. 4)A thread executes only the code inside the run() method. It can never execute other methods unless they are called from run(). 349
  • 350.
    Multithreading In Java MultiTasking Using Threads In multi tasking, several tasks are executed at a time. For this purpose we need more than one thread. For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks. Then those tasks are simultaneously executed by two threads. This is called as multi threading 350
  • 351.
    Multithreading In Java Whenwe go to a movie theatre, generally a person is there at the door-checking and cutting the tickets. When we enter the hall, there is another person who shows the seats for us. Suppose there is only one person (1 thread) doing these two tasks. He has to first cut the ticket and then come along with us to show the seat. Then he goes back to the door to cut the second ticket and then again enter the hall to show the seat for second ticket. Like this, if he is does the things one by one, it takes a lot of time, and even though the show is over, there will be still a few people left outside the door waiting to enter the hall. The solution is theatre management employ two persons(2 threads) for this purpose. The first person will cut the ticket, and the second person will show the seat. When the second person is showing the seat, the first person cut the second ticket. Like this, both the persons can act simultaneously and hence there will be no wastage of time. 351
  • 352.
    Multithreading In Java MultipleThreads Acting on Single Object • Multiple threads acting on single object means two or more threads should share the same object (same run() method). In this case we get unreliable results • For example, take the case of railway reservation system. Everyday several people want reservation of a berth for them. The procedure to reserve the berth is same for all the people. So we need same object with same run() method to be executed repeatedly for all the people • Let us think that only one berth is available in a train, and two passengers are asking that berth. In reservation counter no.1, the clerk has sent a request to the server to allot that berth to his passenger. In counter no.2, the second clerk has also sent a request to the server to allot that berth to his passenger. Let us see now to whom that berth is allotted. 352
  • 353.
    Multithreading In Java ThreadSynchronization  Whenever multiple threads are trying to use same resource than they may be chance to of getting wrong output, to overcome this problem thread synchronization can be used.  Allowing only one thread at a time to utilized the same resource out of multiple threads is known as thread synchronization or thread safe.  In java thread synchronization can be achieve in two different ways.  Synchronized block  Synchronized method 353
  • 354.
    Multithreading In Java Synchronizedblock • Whenever we want to execute one or more than one statement by a single thread at a time(not allowing other thread until thread one execution is completed) than those statement should be placed in side synchronized block. 354
  • 355.
    Multithreading In Java Synchronizedmethod • Whenever we want to allow only one thread at a time among multiple thread for execution of a method than that should be declared as synchronized method. 355
  • 356.
  • 357.
    Multithreading In Java Differencebetween synchronized keyword and synchronized block When we use synchronized keyword with a method, it acquires a lock in the object for the whole method. It means that no other thread can use any synchronized method until the current thread, which has invoked it's synchronized method, has finished its execution. synchronized block acquires a lock in the object only between parentheses after the synchronized keyword. This means that no other thread can acquire a lock on the locked object until the synchronized block exits. But other threads can access the rest of the code of the method. Which is more preferred - Synchronized method or Synchronized block? In Java, synchronized keyword causes a performance cost. A synchronized method in Java is very slow and can degrade performance. So we must use synchronization keyword in java when it is necessary else, we should use Java synchronized block that is used for synchronizing critical section only. 357
  • 358.
    Multithreading In Java Deadlockin threads • Deadlock is a situation of complete Lock, when no thread can complete its execution because lack of resources. In the b picture, Thread 1 is holding a resource R1, and need another resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock. 358
  • 359.
  • 360.
    Multithreading In Java •To book a ticket, the thread will enter the train object to verify that the ticket is available or not. When there is a ticket, it updates the available number of tickets in the train object. For this, it takes, 150 milliseconds. Then it enters the compartment object. In compartment object, it should allot the ticket for the passenger and update its status to reserved. This means the thread should go through both the train and compartment objects. • Let us think if a thread has to cancel a ticket, it will first enter compartment object, and updates the status of the ticket as available. For this it is taking 200 milliseconds. Then it enters train object and updates the available number of tickets there. So, this thread also should go through both the compartment and train objects 360
  • 361.
    Multithreading In Java •When BookTicket thread is at train object for 150 milliseconds, the CancelTicket thread will be at compartment object for 200 milliseconds. We are using multiple threads we should synchronize them. So, the threads will lock those objects • When 150 milliseconds time is over, BookTicket thread tries to comeout of train object and wants to lock on compartment object, by entering it.At that time, it will find that the comaprtment object is already locked by another thread(CancelTicket) and hence it will wait, BookTicket thread will wait for compartment object for another 50 milliseconds. • After 200 milliseconds time is up, the CancelTicket thread which is in compartment object completes its execution and wants to enter and lock on train object. But it will find that the train object is laready under lock by BookTicket thread and hence is not available. Now, CancelTicket will wait for the train object which should be unlocked by BookTicket. • Both the threads will wait forever in this way, suspending any further execution. This situation is called ‘Thread Deadlock’. 361
  • 362.
    Multithreading In Java ThreadPriorities 1)Every thread in Java has a priority that helps the thread scheduler to determine the order in which threads scheduled. 2)The threads with higher priority will usually run before than lower priority threads. 3)By default, all the threads had the same priority. 4)However, you can explicitly set a thread's priority at any time after its creation by calling its setPriority() method. 5)This method accepts an argument of type int that defines the new priority of the thread. Its syntax is. final void setPriority(int priority) 362
  • 363.
    Multithreading In Java 6)Priority is an integer value that must range between 1 and 10, with 10 being the highest priority, 1 being the lowest and 5 being the default. 7) If you specify a priority that is out of range, then an IllegalArgumentException exception thrown. 8) Some thread priorities are static member variables of java.lang.Thread class. 9) These include MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY representing values 1,5 and 10 respectively. 10) The priority of the main thread is Thread.NORM_PRIORITY, i.e., 5. NOTE: Generally higher priority threads can be expected to be given preference by the thread scheduler over lower priority threads. However, the implementation of thread schduling is left upto the JVM implementation. 363
  • 364.
  • 365.
    Multithreading In Java TheMethods to Prevent a Thread from Execution We can prevent(stop) a Thread execution by using the following methods. 1)yield(); 2)join(); 3)sleep(); 365
  • 366.
    Multithreading In Java yield()method 1)yield() method causes "to pause current executing Thread for giving the chance of remaining waiting Threads of same priority". 2)If all waiting Threads have the low priority or if there is no waiting Threads then the same Thread will be continued its execution. 3)If several waiting Threads with same priority available then we can't expect exact which Thread will get chance for execution. 4)The Thread which is yielded when it get chance once again for execution is depends on mercy of the Thread scheduler. public static native void yield() Note : Some operating systems may not provide proper support for yield() method. 366
  • 367.
  • 368.
    Multithreading In Java join()method If a Thread wants to wait until completing some other Thread then we should go for join() method. Example: If a Thread t1 executes t2.join() then t1 should go for waiting state until completing t2. Note Every join() method throws InterruptedException, which is checked exception hence compulsory we should handle either by try catch or by throws keyword. 368
  • 369.
  • 370.
    Multithreading In Java Youhave three threads T1, T2, and T3, How do you ensure that they finish in order T1, T2, T3 ?. You can do this by using join method, by calling T1.join() from T2 and T2.join() from T3. In this case thread, T1 will finish first, followed by T2 and T3. 370
  • 371.
    Multithreading In Java sleep()method If a Thread don't want to perform any operation for a particular amount of time then we should go for sleep() method. public static native void sleep(long ms) throws InterruptedException public static void sleep(long ms,int ns)throws InterruptedException 371
  • 372.
  • 373.
    Multithreading In Java Interruptinga Thread How a Thread can interrupt another thread ? If a Thread can interrupt a sleeping or waiting Thread by using interrupt()(break off) method of Thread class. public void interrupt() Note 1) Whenever we are calling interrupt() method we may not see the effect immediately, if the target Thread is in sleeping or waiting state it will be interrupted immediately. 2) If the target Thread is not in sleeping or waiting state then interrupt call will wait until target Thread will enter into sleeping or waiting state. Once target Thread entered into sleeping or waiting state it will effect immediately. 3) In its lifetime if the target Thread never entered into sleeping or waiting state then there is no impact of interrupt call simply interrupt call will be wasted. 373
  • 374.
    Multithreading In Java DaemonThread Java defines two types of thread: user thread (normal thread) and daemon thread. By default, when you create a new thread it is user thread. The Java Virtual Machine (JVM) won’t terminate if there are still user threads running. But it will exit if there are only daemon threads running. Daemon threads have lower priority than normal ones, so they are used for running background services that serve user threads. An example of daemon thread in the JVM is the garbage collector thread that runs silently in the background to free unused memory. 374
  • 375.
    Multithreading In Java Methodsof Thread class that are related to Daemon threads: public void setDaemon(boolean status) This method is used for making a user thread to Daemon thread or vice versa. For example if I have a user thread t then t.setDaemon(true) would make it Daemon thread. On the other hand if I have a Daemon thread td then by calling td.setDaemon(false) would make it normal thread(user thread/non-daemon thread). public boolean isDaemon() This method is used for checking the status of a thread. It returns true if the thread is Daemon else it returns false. 375
  • 376.
    Multithreading In Java Note setDaemon()method can only be called before starting the thread. This method would throw IllegalThreadStateException if you call this method after Thread.start() method. 376
  • 377.
    Multithreading In Java InterThread Communication Polling Problem The process of testing a condition repeatedly till it becomes true is known as polling. Example Suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waits for the producer to produce. Once the producer has finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. 377
  • 378.
    Multithreading In Java Thesolution for polling problem is inter-thread communication Inter-thread communication Inter-thread communication is a process in which a thread is paused running in its critical region and another thread is allowed to enter (or lock) in the same critical region to be executed. i.e. synchronized threads communicate with each other. For inter-thread communication java provides three methods they are wait(), notify() and notifyAll(). All these methods belong to object class as final so that all classes have them. They must be used within a synchronized block only. 378
  • 379.
    Multithreading In Java •wait()-It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify(). • notify()-It wakes up one single thread that called wait() on the same object. It should be noted that calling notify() does not actually give up a lock on a resource. • notifyAll()-It wakes up all the threads that called wait() on the same object. 379
  • 380.
    Multithreading In Java ThreadGroupin Java 1)A ThreadGroup represents a set of threads. So we can suspend, resume or interrupt group of threads by a single method call. 2)A thread group can also include the other thread group. The thread group creates a tree in which every thread group except the initial thread group has a parent. 3)A thread is allowed to access information about its own thread group, but it cannot access the information about its thread group's parent thread group or any other thread groups. 4)Java thread group is implemented by java.lang.ThreadGroup class. 380
  • 381.
  • 382.
    Multithreading In Java Constructorsof ThreadGroup class ThreadGroup(String name) creates a thread group with given name. ThreadGroup base = new ThreadGroup("Base"); ThreadGroup(ThreadGroup parent, String name) creates a thread group with given parent group and name. ThreadGroup group1 = new ThreadGroup(base, "Group1"); 382
  • 383.
    Multithreading In Java Importantmethods of ThreadGroup class activeCount():returns an estimate of the number of active threads in the thread group and its subgroups. destroy():destroys the thread group and all of its subgroups. enumerate(Thread[] list):copies into the specified array every active thread in this thread group and its subgroups. getMaxPriority():returns the maximum priority of the thread group. interrupt():interrupts all threads in the thread group. isDaemon():tests if the thread group is a daemon thread group. setMaxPriority(int priority): sets the maximum priority of the group. 383
  • 384.
    Multithreading In Java ThreadPool 1)In terms of performance, creating a new thread is an expensive operation because it requires the operating system allocates resources need for the thread. 2)Instead of creating new threads when new tasks arrive, a thread pool keeps a number of idle threads that are ready for executing tasks as needed. After a thread completes execution of a task, it does not die. Instead it remains idle in the pool waiting to be chosen for executing new tasks. 3)You can limit a definite number of concurrent threads in the pool, which is useful to prevent overload. If all threads are busily executing tasks, new tasks are placed in a queue, waiting for a thread becomes available. 384
  • 385.
    Multithreading In Java TheJava Concurrency API supports the following types of thread pools: 1)Cached thread pool: keeps a number of alive threads and creates new ones as needed. 2)Fixed thread pool: limits the maximum number of concurrent threads. Additional tasks are waiting in a queue. 3)Single-threaded pool: keeps only one thread executing one task at a time. 4)Fork/Join pool: a special thread pool that uses the Fork/Join framework to take advantages of multiple processors to perform heavy work faster by breaking the work into smaller pieces recursively. 385
  • 386.
    Multithreading In Java Whatis an Executor? An Executor is an object that is responsible for threads management and execution of Runnable tasks submitted from the client code. It decouples the details of thread creation, scheduling, etc from the task submission so you can focus on developing the task’s business logic without caring about the thread management details. That means, rather than creating a thread to execute a task like this: Thread t = new Thread(new RunnableTask()); t.start(); You submit tasks to an executor like this: Executor executor = anExecutorImplementation; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); 386
  • 387.
    Multithreading In Java TheJava Concurrency API defines the following 3 base interfaces for executors: 1)Executor: is the super type of all executors. It defines only one method execute(Runnable). 2)ExecutorService: is an Executor that allows tracking progress of value-returning tasks (Callable) via Future object, and manages the termination of threads. Its key methods include submit() and shutdown(). 3)ScheduledExecutorService: is an ExecutorService that can schedule tasks to execute after a given delay, or to execute periodically. Its key methods are schedule(), scheduleAtFixedRate() and scheduleWithFixedDelay(). 387
  • 388.
    Multithreading In Java Youcan create an executor by using one of several factory methods provided by the Executors utility class. 1) newCachedThreadPool(): creates an expandable thread pool executor. New threads are created as needed, and previously constructed threads are reused when they are available. Idle threads are kept in the pool for one minute. This executor is suitable for applications that launch many short-lived concurrent tasks. 2) newFixedThreadPool(int n): creates an executor with a fixed number of threads in the pool. This executor ensures that there are no more than n concurrent threads at any time. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread becomes available. If any thread terminates due to failure during execution, it will be replaced by a new one. The threads in the pool will exist until it is explicitly shutdown. Use this executor if you and to limit the maximum number of concurrent threads. 388
  • 389.
    Multithreading In Java 3)newSingleThreadExecutor(): creates an executor that executes a single task at a time. Submitted tasks are guaranteed to execute sequentially, and no more than one task will be active at any time. Consider using this executor if you want to queue tasks to be executed in order, one after another. 4) newScheduledThreadPool(int corePoolSize): creates an executor that can schedule tasks to execute after a given delay, or to execute periodically. Consider using this executor if you want to schedule tasks to execute concurrently. 5) newSingleThreadScheduleExecutor(): creates a single-threaded executor that can schedule tasks to execute after a given delay, or to execute periodically. Consider using this executor if you want to schedule tasks to execute sequentially. 389
  • 390.
  • 391.
  • 392.
  • 393.
  • 394.
  • 395.
  • 396.
    Collection framework What isa collection? In terms of programming, a collection is a data structure that holds a set of objects in a specific manner. It looks like arrays but collections are more advanced and more flexible. An array simply stores a fixed number of objects, whereas a collection stores variable number of objects dynamically, i.e. you can add or remove objects as you wish. A collection also provides useful operations such as adding, removing, retrieving objects. 396
  • 397.
    Collection framework What isCollection Framework 1)A Collection Framework in Java is a unified architecture that represents a collection of interfaces and classes. It helps in storing and processing the data efficiently. 2)Java Collections Framework provides useful and robust algorithms such as searching and sorting on collections, and the interoperability between collections and arrays. 3)The Java collections framework provides various data structures and algorithms that can be used directly. It means we do not have to write code to implement these data structures and algorithms manually. 4)The two principal root interfaces of Java collection classes are Collection interface and Map interface . 397
  • 398.
  • 399.
    Collection framework Collection Interface TheCollection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. 399
  • 400.
    Collection framework Some importantmethods of Collection interface 400 S.No Method Name Description 1 boolean add(Object obj) Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, when that collection does not allow duplicates. 2 boolean addAll(Collection c) Adds all the elements of c to the invoking collection. Returns true if the operation succeeds (i.e., the elements were added). Otherwise, returns false. 3 void clear( ) Removes all elements from the invoking collection. 4 boolean contains(Object obj) Returns true if obj is an element of the invoking collection. Otherwise, returns false.
  • 401.
    Collection framework 5 booleancontainsAll(Collection c) Returns true if the invoking collection contains all elements of c. Otherwise, returns false. 6 boolean equals(Object obj) Returns true if the invoking collection and obj are equal. Otherwise, returns false. 7 int hashCode( ) Returns the hash code for the invoking collection. 8 boolean isEmpty( ) Returns true if the invoking collection is empty. Otherwise, returns false. 9 Iterator iterator( ) Returns an iterator for the invoking collection. 10 boolean remove(Object obj) Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false. 11 boolean removeAll(Collection c) Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. 401
  • 402.
    Collection framework 12 booleanretainAll(Collection c) Removes all elements from the invoking collection except those in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. 13 int size( ) . Returns the number of elements held in the invoking collection 14 Object[ ] toArray( ) Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements. 15 Object[ ] toArray(Object array[ ]) Returns an array containing only those collection elements whose type matches that of array. 402
  • 403.
  • 404.
  • 405.
  • 406.
  • 407.
  • 408.
  • 409.
  • 410.
  • 411.
  • 412.
  • 413.
  • 414.
  • 415.
  • 416.
  • 417.
  • 418.
  • 419.
  • 420.
  • 421.
  • 422.
  • 423.
  • 424.
  • 425.
  • 426.
  • 427.
  • 428.
  • 429.
    JVM Architecture • Firstof all, the .java program is converted into a .class file consisting of byte code instructions by the Java compiler • JVM(Java Virtual Machine) is responsible for taking the .class file and converting each byte code instruction into the machine language instruction that can be executed by the processor 429
  • 430.
  • 431.
    JVM Architecture • InJVM, there is a program called classloader sub system, which performs the following functions 1)First of all, it loads the .class file into memory 2)Then it verifies whether all byte code instructions are proper or not. If it finds any instruction suspicious, the execution is rejected immediately 3)If the byte code instructions are proper, then it allocates necessary memory to execute the program • This memory divided into 5 parts, called run time data areas 431
  • 432.
    JVM Architecture Method area •It is the memory block, which stores the class code, code of the variables, and code of the methods in the Java program Heap • This is the area where objects are created. Whenever JVM loads a class, a method and a heap area are immediately created in it. 432
  • 433.
    JVM Architecture Java Stacks •Method code stored on Method area. But while running a method, it needs some more memory to store the data and results. This memory is allocated on Java stacks. So, Java Stacks are memory areas where Java methods are executed. 433
  • 434.
    JVM Architecture PC(Program Counter)registers • These are the registers which contain memory address of the instructions of the methods. If there are 3methods, 3 PC registers will be used to track the instructions of the methods Native method stacks • Java method are executed on Java stacks. Similarly, native methods(C/C++ functions) are executed on Native method stacks. To execute native methods, native method libraries are required. These header files are located and connected to JVM by a program, called Native method interface 434
  • 435.
  • 436.
    Factory Methods • Factorymethods are static methods only • A factory method is a method that creates and returns an object to the class to which it belongs. • The aim of factory method is to create an object depending on the user option. Example :public static Fees getFees(String course) { } Above method takes the course from the user and creates an object either to CSE class or ECE class depending on the user option 436
  • 437.
  • 438.
    Different Ways ObjectCreation In Java 1) Using new operator Employee obj=new Employee(); 2) Using factory methods NumberFormat obj=NumberFormat.getNumberInstance(); 3) Using newInstance() method Class c=Class.forName(“Employee”); Empoyee obj=(Employee)c.newInstance(); 4) By cloning an already available object Employee obj1=new Employee(); Employee obj2=(Employee)obj1.clone(); 438
  • 439.
  • 440.
    Object Class 1) Thereis a class with the name ‘Object’ I java.lang package which is the super class of all classes in Java 2) Every class in Java is a direct or indirect sub class of the Object class 3) The Object class defines the methods to compare objects, to convert an object into String, etc. 440
  • 441.
    Object Class Methods ofObject class 441 Method Description equals() Compares the references of two objects return true when they are equal otherwise return false toString() Returns a string representation of an object getClass() It gives an object that contains the name of a class to which an object belongs hashCode() Returns hashcode number of an object notify() Sends a notification to a thread which is waiting for an object notifyAll() Sends a notification for all waiting threads for the object wait() Causes a thread to wait till a notification is received from a notify() or notifyAll() methods
  • 442.
    Object Class equals() method 1)Thismethod normally compares the references of two objects 2)If both the references refer to same object, then it gives true, otherwise it gives false 3)But in case of String objects and wrapper class objects it compares the contents of the objects 4)If the content are same then it returns true, otherwise false 442
  • 443.
    Object Class hashCode() method 1)Wheneverit is invoked on the same object more than once during an execution of a Java application, the hashCode() method must consistently return the same integer 2)If two objects are equal according to the equals() method, then calling the hashCode() method on each of the two objects must produce the same integer result 3)If two objects are unequal according to the equals() method, then calling the hashCode() method on each of the two objects must produce distinct integer results 443
  • 444.
  • 445.
    Exception Propagation • Consideringa scenario, in which your program starts its execution at the main() method, main() calls method1(), method1() calls method2(), method2() calls method3(), now the call stack should look like 445
  • 446.
    Exception Propagation • Thecurrently executing method is at the top of the call stack, which in this example is method3(). Let's say while executing method3(), an exception is raised/thrown. Now this exception is thrown down to the next method in the call stack, i.e. method2(), which in turn throws the exception down to next method in the call stack, i.e. method1(). The process continues until the exception is thrown to the method at the bottom of the call stack, i.e. main() method. 446
  • 447.
    Exception Propagation • Thecurrently executing method is at the top of the call stack, which in this example is method3(). Let's say while executing method3(), an exception is raised/thrown. • Now this exception is thrown down to the next method in the call stack, i.e. method2(), which in turn throws the exception down to next method in the call stack, i.e. method1(). • The process continues until the exception is thrown to the method at the bottom of the call stack, i.e. main() method. This is called as exception propagation Note: • Only unchecked exceptions are propagated. Checked exceptions throw compilation error. 447
  • 448.
  • 449.
    Try-With-Resource Syntax try(resource-specification(there can bemore than one resource)) { //use the resource } catch() { ... } 449
  • 450.
    Try-With-Resource • This trystatement contains a parenthesis in which one or more resources is declared. • A resource is an object that is used in program and must be closed after the program is finished. • The try-with-resources statement ensures that each resource is closed at the end of the statement of the try block. You do not have to explicitly close the resources. 450
  • 451.
  • 452.
    Catch multiple exceptions •In Java 7 it was made possible to catch multiple different exceptions in the same catch block. try { // execute code that may throw 1 of the 3 exceptions below. } catch(SQLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } 452
  • 453.
    Catch multiple exceptions try{ // execute code that may throw 1 of the 3 exceptions below. } catch(SQLException | IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } 453
  • 454.
  • 455.
    Rethrowing The Exeption •There might be situations in your program where you want to both catch an exception in your code and also want its caller be notified about the exception. • This is possible by rethrowing the exception using throw statement. 455
  • 456.
  • 457.
    Thread Deadlock • Deadlockis a situation of complete Lock, when no thread can complete its execution because lack of resources. In the above picture, Thread 1 is holding a resource R1, and need another resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock. 457
  • 458.
  • 459.
  • 460.
    Interthread Communication Polling Problem Theprocess of testing a condition repeatedly till it becomes true is known as polling. Example Suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waits for the producer to produce. Once the producer has finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. 460
  • 461.
    Inter-thread communication The solutionfor polling problem is inter-thread communication Inter-thread communication Inter-thread communication is a process in which a thread is paused running in its critical region and another thread is allowed to enter (or lock) in the same critical region to be executed. i.e. synchronized threads communicate with each other. For inter-thread communication java provides three methods they are wait(), notify() and notifyAll(). All these methods belong to object class as final so that all classes have them. They must be used within a synchronized block only. 461
  • 462.
    Interthread Communication • wait()-Ittells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify(). • notify()-It wakes up one single thread that called wait() on the same object. It should be noted that calling notify() does not actually give up a lock on a resource. • notifyAll()-It wakes up all the threads that called wait() on the same object. 462
  • 463.
  • 464.
    Daemon Thread • Daemonthreads are low priority threads which are act as a service provider for user threads. Life of a daemon thread is depends upon the user threads. JVM automatically terminates daemon thread when all user threads are died. Daemon threads are used for background supporting tasks. Methods used for daemon threads: 1. public final void setDaemon(boolean on) Marks this thread as daemon thread if on is true. 2. public final boolean isDaemon() Returns true if thread is daemon. 464
  • 465.
  • 466.
    Java Annotations • Javaannotations were added to Java from Java 5. • Java annotations are used to provide the meta data to our Java code. • Meta data is the additional information which can be used for any class, interface, method or field. • Java annotations can be used as an alternative option for XML and java marker interfaces. 466
  • 467.
    Java Annotations Java annotationsare mainly used for the following: Compiler instructions used to give certain instructions to the compiler Build-time instructions can be used by the build tools for generating source code, generating XML files, packaging the compiled code and files into a JAR file etc. Runtime instructions These annotations can be accessed using Java Reflection. 467
  • 468.
    Java Annotations • Ajava annotation always starts with the symbol @ and followed by the annotation name Syntax: Example: @AnnotationName @Entity • An annotation can contain zero, one or multiple elements. We have to set values for these elements. Example: @Entity(tableName = "USERS") We can use java annotations above classes, interfaces, methods, fields and local variables. Here is an example annotation added above a class definition: 468
  • 469.
    Java Annotations Java AnnotationsList: • @Deprecated • @Override • @SuppressWarnings • @Target • @Retention • @Inherited • @Documented 469
  • 470.
    Java Annotations @Deprecated javaannotation • The deprecated terms in software development is refers to classes, interfaces, functions or elements that are in the process of being replaced by newer ones. • The @Deprecated java annotation signals that the marked element is deprecated and should no longer be used. 470
  • 471.
    Java Annotations @Override javaannotation • The @Override java annotation indicates that the subclass method is overriding the parent class method. • If we are not using override annotation it may be the case someone changed the name of the overridden method in the superclass, in that case subclass method would no longer override it. 471
  • 472.
    Java Annotations @SuppressWarningsjava annotation •The @SuppressWarnings annotation type allows Java programmers to disable compilation warnings for a certain part of a program (type, field, method, parameter, constructor, and local variable). 472
  • 473.
  • 474.
  • 475.
    Object Oriented Programming Whatis object oriented programming? • Object-Oriented Programming is a programming pattern that makes use of objects and their interactions to design and implement applications • Objects are entities that serve as the basic building blocks of an object-oriented application • An object is a self-contained entity with attributes and behaviors 475
  • 476.
  • 477.
    Object Oriented Programming Whatis an Object?  An entity which does exist, has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc.  If something does not really exist, then it is not an object e.g. our thoughts, imagination, plans, ideas etc.,  According to System existence means contains memory. So a software object represent a memory.  Software objects also have a state and a behavior. A software object's state is stored in variables and behavior is shown via methods. So an object contains variables and methods 477
  • 478.
    Object Oriented Programming Whatis a Class?  It is possible that some objects may have similar properties and actions. Such objects belongs to same category called a ‘class’  It is only an logical component and not the physical entity e.g. if you had a class called “Expensive Cars” it could have objects like Mercedes, BMW, Toyota, etc.  Its properties(data) can be price or speed of these cars.  While the methods may be performed with these cars are driving, reverse, braking etc. 478
  • 479.
  • 480.
    Object Oriented Programming Whatis an abstraction in Java? In object oriented programming abstraction is a process of providing functionality to the users by hiding its implementation details from them In other words, the user will have just the knowledge of what an entity is doing instead of its implementation 480
  • 481.
    Object Oriented Programming Reallife example of Abstraction is ATM Machine; All are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about ATM. 481
  • 482.
  • 483.
    Object Oriented Programming Howto Achieve Abstraction in Java? In Java, we can achieve Data Abstraction using Abstract class and Interface Interface allow 100% abstraction(complete abstraction). Interface allow you to abstract the implementation completely Abstract class allow 0 to 100% abstraction (partial to complete abstraction)because abstract class can contain concrete methods that have the implementation which results in a partial abstraction 483
  • 484.
    Object Oriented Programming Whatis an Encapsulation? 1)We can define it as Encapsulation is the wrapping up of data and functions (methods that operate on the data) into a single unit (called class). 2)There is a prohibition for direct access to the data. Functions (that combine with the data) are the only way to access data. These functions are the member functions or methods in Java. It basically creates a shield due to which the code or data cannot be accessed outside the shield. 3)In Java class bind the data with its associated method so class is an example of encapsulation 484
  • 485.
  • 486.
    Object Oriented Programming AchievingEncapsulation in Java In order to achieve encapsulation in Java, we have to 1)declare the variables of a class as private, so that they cannot be accessed directly from outside the class. 2)provide setter and getter methods that are declared as public, to view and change the values of the variables. 486
  • 487.
    Object Oriented Programming Inheritancein Java 1)The process by which one class acquires the properties(data members) and functionalities(methods) of another class is called inheritance. 2)In the inheritance the class which is give data members and methods is known as base or super or parent class. 3)The class which is taking the data members and methods is known as sub or derived or child class 487
  • 488.
  • 489.
    Object Oriented Programming Polymorphismin Java Polymorphism is the ability for a data or message to be processed in more than one form. It is a concept by which a single operation can be performed in multiple different ways. For example, a security guard outside an organization behaves differently with different people entering the organization. He acts in a different way when the Boss comes and, in another way when the employees come. When the customers enter, the guard will respond differently. So here, the behavior of the guard is in various forms, which depends on the member who is coming. 489
  • 490.
  • 491.
    Object Oriented Programming Wecan define polymorphism in the context of Object-Oriented Programming as follows: “The virtue (good future) by which the same action can be performed by objects of different classes and each object responds in a different way depending on its class is called Polymorphism”. 491
  • 492.
  • 493.
  • 494.
  • 495.
  • 496.
  • 497.
  • 498.
    Wrapper Classes 1) Awrapper class is a class whose object contains or wraps a primitive data type 2) When we create an object to a wrapper class, it contains a field and in this field, we can store a primitive data type 3) For example, if we create an object to Character wrapper class, it contains a single field char and it is possible to store a character like ‘a’ Need of Wrapper classes 1) Wrapper classes convert primitive data type into object and this is needed on internet to communicate between two applications 2) The classes in java.util package handle only objects hence wrapper classes help in this case also 498
  • 499.
  • 500.
  • 501.
    Wrapper Classes Number class Numberis an abstract class whose sub classes are Byte, Short,Integer,Long,Float and Double So the methods of Number class are commonly available in all these classes Methods of Number class byte byteValue() Converts the calling object into byte value short shortValue() Converts the calling object into short value int intValue() Converts the calling object into int value 501
  • 502.
    Wrapper Classes long longValue() Convertsthe calling object into long value float floatValue() Converts the calling object into float value double doubleValue() Converts the calling object into double value Note The calling object can be an object of Byte, Short, Integer, Long, Float or Double class 502
  • 503.
    Wrapper Classes Character Class Thecharacter class wraps a value of the primitive type char in an object. Character class has only one constructer which accepts primitive data type Character obj=new Character('A'); Important methods of Character class char charvalue ( ):used to convert character object into character primitive character obj=new character ('A'); char ch=obj charValue(); int compare To (character obj):useful to compare two character objects int x =obj1.compare (obj2); if obj1==obj2,returns 0 if obj1<obj2,returns negative value if obj1>obj2,returns positive value String toString( ):converts character object into string object 503
  • 504.
    Wrapper Classes static Charactervalue Of (char ch) convert a single character ch into character ch into character object static boolean isDigit (char ch) returns true if ch is a digit otherwise return false static boolean isLetter(char ch) returns true if ch is a letter static boolean isUpperCase(char ch) returns true if ch is a uppercase letter static boolean isLowerCase(char ch) returns true if ch is lower case letter 504
  • 505.
    Wrapper Classes static booleanisSpaceChar(char ch) returns true if ch is represents a white space static boolean isLetterorDigit(char ch) returns true if ch either a letter or digit static char toUpperCase(char ch) converts ch into uppercase static char toLowerCase(char ch) converts ch into lowercase 505
  • 506.
    Wrapper Classes Byte Class Thebyte class wraps a value of primitive type 'byte‘ in an object. Constructors 1)Byte(byte num): create byte object as Byte obj=new Byte(120); 2)Byte(String str): create Byte object by converting a string that contains a byte number Byte obj=new Byte("120"); 506
  • 507.
    Wrapper Classes Important methodsof Byte class int compareTo(Byte b) useful to compare the contents of Byte class objects. int x=obj1.comareTo(obj2); obj1==obj2 returns 0 obj1<obj2 returns negative value obj1>obj2 returns positive value boolean equals(object obj) compares the Byte object with any other object obj.If both have same content then it returns true otherwise false. static byte parseByte(String str) returns the primitive byte number contained in the string str. 507
  • 508.
    Wrapper Classes String toString() convertsByte object into string object and returns that string object static Byte valueOf(String str) converts string str that contains some byte number into Byte class object static Byte valueOf(byte b) converts the primitive byte b into Byte object. 508
  • 509.
    Wrapper Classes Short Class Shortclass wraps a value of primitive data type 'short' in its object. Constructors Short(short num) Takes short number as its parameter and convert it into Short class object. short s=14007; Short obj=new Short(s); Short(String str) Useful to construct the short class object by passing string str to it as String str="2756"; Short obj=new Short(str); 509
  • 510.
    Wrapper Classes Important methodsof Short class int compareTo(Short obj) Compare the numeric value of two short class objects and return 0,-ve value or +ve value. boolean equals(Object o) Compares the Short object with any other object o.if both have the same content then it returns true otherwise false. static short parseShort(String str) returns short equivalent of the string str. String toString() returns a string form of the Short object. static Short valueof(String str) Converts a string str that contains some short number into Short class object and returns that object. 510
  • 511.
    Wrapper Classes Integer Class Theinteger class wraps a value of the primitive int number as its parameter and converts it into integer class object Constructors Integer(int num): creates integer object Integer obj= new Integer(123000); here, we are converting a primitive int value into integer object. This is called 'boxing’ Integer(String str): create an Integer object by converting a string that contains as int number Integer obj = new Integer("198663"); 511
  • 512.
    Wrapper Classes Important methodsof Integer class int compareTo(Integer obj) compares the numerical value of two integer class objects and returns 0,+ve value ,or -ve value boolean equals(object obj) compare the inter object with any other object if both have the same content,then it returns true otherwise false. static int parseInt(String str) returns int equivalent of the string str. String toString() returns a string form of the integer object. static Integer valueOf(String str) convert a string str that contains some int number into integer class object and returns that object. 512
  • 513.
    Wrapper Classes static StringtoBinaryString(int i) converts decimal integer number i into binary umber system and returns that binary number as a string static String toHexString(int i) converts decimal integer number i into hexadecimal number system and returns that hexdecimal number as a string static String toOctalString(int i) converts decimal integer number i into octal number system and returns that octal number as a string int intValue() converts integer object into primitive int type value. This is called 'unboxing'. 513
  • 514.
    Wrapper Classes Long Class TheLong contains a primitive long type data Constructors Long(long num) Long object can be created Long obj=new Long(1230044); Long(String str) Create Long object by converting a string that contains a long number Strung str=“1230044”; Long obj=new Long(str); 514
  • 515.
    Wrapper Classes Important methodsof Long class int compareTo(Long obj) Compares the numeric value of two Long class objects and return 0, -ve value, or +ve value boolean equals(Object obj) Compares the Long object with any other object obj. If both have same content, then it returns true otherwise false static long parseLong(String str) Return long equivalent of the string str String toString() Converts Long object into String Object static Long valueOf(String str) Converts a string str that contains some long number into Long object 515
  • 516.
    Wrapper Classes Math Class Theclass Math contains methods for performing basic numeric operations, such as the elementary exponential, square root etc.. All the methods of Math class are static Important methods of Math class static double sin(double arg) return the sine value of the arg Math.sin(0.5);//0.4794255 static double cos(double arg) return the cosine value of the arg Math.cos(0.5);//0.87758256189 static double tan(double arg) return the tanget value of the arg Math.tan(0.5);//0.54630248 516
  • 517.
    Wrapper Classes static doublelog(double arg) return the natural logarithm value of the arg Math.log(0.5);//-0.69314718055 static double log10(double arg) return the base10 algorithm value of the arg Math.log10(0.5);//-0.30102999566 static double pow(double x, double n) return the x to the power of the n value Math.pow(5,3);//125.0 static double sqrt(double arg) return the square root of the arg Math.sqrt(25);//5.0 517
  • 518.
    Wrapper Classes static doubleabs(double arg) return the absolute value of the arg . Absolute value present the positive quantity Math.abs(-4.55);//4.55 static double ceil(double arg) raises the given arg value to the next integer value. If integer is given to this method, it gives same value Math.ceil(4.5);//5.0 static double floor(double arg) decreases the given arg value to the previous integer value. If integer is given to this method, then it gives the same value, Math.floor(4.5); //4.0 static double min(arg1,arg2) returns the minimum of arg1 and arg2 Math.min(5,10); //5.0 518
  • 519.
    Wrapper Classes static doublemax(arg1,arg2) returns the maximum of arg1 and arg2 Math.max(5,10); //10.0 static long round(arg) returns the rounded value of arg. If the fraction part of the number is more or equal to 0.5,then 1 is added to the integer part; otherwise the same integer part is returned. Math.round(4.6);//5 Math.round(4.4);//4 static double random() returns a random number between 0 and 1.A random number is a number that cannot be guessed by anyone. Math.random();//0.2230762209 519
  • 520.
    Wrapper Classes static doubletoRadians(double angle) converts the given value in degree into radians. Math.toRadians(180);//3.141592653 static double to Degree(double angle) converts angle in radians into degree. Math.toDegree(3.14159);//179.9998479 520
  • 521.
    Wrapper Classes Double class TheDouble class wraps a value of the primitive type double in an object. The double class object contains a double type field that stores a primitive double number Constructors Double (double num) Double object can be created double d=12.1223; Double obj=new Double(d); Double (String str) This constructor is useful to create a Double object by converting a string that contains a double number String str=“12.1223”; Double obj=new Double(str); 521
  • 522.
    Wrapper Classes Important methodsof Double class int compareTo(Double obj) Compares the numeric value of two Double class objects and return 0, - ve value, or +ve value boolean equals(Object obj) Compares the Double object with any other object obj. If both have same content, then it returns true otherwise false static double parseDouble(String str) Return double equivalent of the string str String toString() Converts Double object into String Object static Double valueOf(String str) Converts a string str that contains some double number into Double object 522
  • 523.
    Wrapper Classes Float class TheFloat class wraps a value of the primitive type float in an object. The Float class object contains a float type field that stores a primitive float number Constructors Float (float num) Float object can be created float f=12.122f; Float obj=new Float(f); Float (String str) This constructor is useful to create a Float object by converting a string that contains a float number String str=“12.122f”; Float obj=new Float(str); 523
  • 524.
    Wrapper Classes Important methodsof Float class int compareTo(Float obj) Compares the numeric value of two Float class objects and return 0, -ve value, or +ve value boolean equals(Object obj) Compares the Float object with any other object obj. If both have same content, then it returns true otherwise false static float parseFloat(String str) Return float equivalent of the string str String toString() Converts Float object into String Object static Float valueOf(String str) Converts a string str that contains some float number into Float object 524
  • 525.
    Wrapper Classes Boolean class TheBoolean class wraps a value of the primitive type boolean in an object. The Boolean class object contains a boolean type field that stores a primitive boolean Constructors Boolean (boolean value) Boolean object can be created Boolean obj=new Boolean(true); Boolean (String str) This constructor is useful to create a Boolean object by converting a string that contains a boolean value String str=“false”; Boolean obj=new Boolean(str); 525
  • 526.
    Wrapper Classes Important methodsof Boolean class int compareTo(Boolean obj) Compares the value of two Boolean class objects and return 0, -ve value, or +ve value boolean equals(Object obj) Compares the Boolean object with any other object obj. If both have same content, then it returns true otherwise false static boolean parseBoolean(String str) Return boolean equivalent of the string str String toString() Converts Boolean object into String Object static Boolean valueOf(String str) Converts a string str that contains some boolean value into Boolean object 526
  • 527.