Introduction to Java.pptx sjskmdkdmdkdmdkdkd

giresumit9 60 views 101 slides Oct 17, 2024
Slide 1
Slide 1 of 101
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101

About This Presentation

Java ppt


Slide Content

Introduction to Programming - Java Girish Godbole

Programming – Introduction & Basics Program A program is a set of instructions given to a computer to perform a specific operation. Software/Computer Programming Software/Computer programming is the act of writing computer code that enables computer software to function. OR Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task History- COBOL (Common Business-Oriented Language) and Fortran were created as one of the first computer languages. COBOL was mainly used to keep track of payrolls, prepare budgets, and track property. Fortran stood for Formula Translator and was used mainly by scientists and engineers. IBM created Fortran in 1957 Purpose – Their objective was to create a programming language that was simpler and to open up computing to more people. The target was to focus more on the problem as compared to the machine’s operations. This computer language is known as the first high-level programming language.

Programming – Introduction & Basics Types of Project /Classification of Software Web based project development Standalone/Desktop based programs/applications Jobs/Schedules Enterprise projects (ERP systems) Database oriented applications Reporting/Analytics applications Artificial Intelligence Software Scientific Software Embedded Software Cloud based projects

Programming – Introduction & Basics Development Lifecycle methodologies Waterfall Model V Model Iterative Model Agile Software Development Spiral Model Rapid Application Development Requirement analysis

Programming – Introduction & Basics Pseudocode Pseudocode is  an informal way of programming description that  does not require any strict programming language syntax or underlying technology considerations. It is used for creating an outline or a rough draft of a program. Pseudocode summarizes a program's flow, but excludes underlying details E.g. Get 10,000 records from DB Filter records based on Category For loop: Process each record for business algorithm Business requirement: Check if each record is created during certain period. If Yes, mark the record as invalid. End For Loop

Java At a Glance Java is one of the most popular and widely used programming languages. Java has been one of the most popular programming languages for many years. Java is Object Oriented. However, it is not considered as pure object-oriented as it provides support for primitive data types (like int, char, etc.) The Java codes are first compiled into byte code (machine-independent code). Then the byte code runs on Java Virtual Machine (JVM) regardless of the underlying architecture. Java syntax is similar to C/C++. But Java does not provide low-level programming functionalities like pointers. Also, Java codes are always written in the form of classes and objects. Java is used in all kinds of applications like Mobile Applications (Android is Java-based), desktop applications, web applications, client-server applications, enterprise applications, and many more. When compared with C++, Java codes are generally more maintainable because Java does not allow many things which may lead to bad/inefficient programming if used incorrectly. For example, non-primitives are always references in Java. So, we cannot pass large objects (like we can do in C++) to functions, we always pass references in Java. One more example, since there are no pointers, bad memory access is also not possible. When compared with Python, Java kind of fits between C++ and Python. The programs are written in Java typically run faster than corresponding Python programs and slower than C++. Like C++, Java does static type checking, but Python does not.

Java At a Glance JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1991, later acquired by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs. Java  is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/ c++ . Naming Conventions in Java Class and Interface:  First letter of each word should be uppercase. Ex: MyClassName . Method:  First letter of first word is lowercase while first letter of other words is uppercase. Ex: myMethodName (). Package and Keyword:  In lowercase. Ex: int, float, static, etc.

Java - Primary/Main Features Platform Independent Object-Oriented Programming Language:  Simple Robust Secure Distributed Multithreading Portables High Performance Dynamic flexibility Sandbox Execution Write Once Run Anywhere Power of compilation and interpretation

Java - Structure JDK(Java Development Kit): JDK is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger. JRE(Java Runtime Environment): JRE contains the parts of the Java libraries required to run Java programs and is intended for end-users. JRE can be view as a subset of JDK. JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms.

Java - Structure

Java - Structure

Programming Toolkit Programming Toolkit Usage of variables and operators Introduction to control constructs Introduction to arrays OOPS (Object Oriented Programing) Concept

Programming Toolkit - Variables Variable in Java is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data. A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In Java, all the variables must be declared before use. Types of Variables local variable instance variable static variable

Programming Toolkit - Variables 1. Local Variables   A variable defined within a block or method or constructor is called a local variable.  These variables are created when the block is entered, or the function is called and destroyed after exiting from the block or when the call returns from the function. The scope of these variables exists only within the block in which the variable is declared. i.e., we can access these variables only within that block. Initialization of the local variable is mandatory before using it in the defined scope. 2. Instance Variables Instance variables are non-static variables and are declared in a class outside any method, constructor, or block.  As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifier for instance variables. If we do not specify any access specifier, then the default access specifier will be used. Initialization of Instance Variable is not Mandatory. Its default value is 0 Instance Variable can be accessed only by creating objects.

Programming Toolkit - Variables Static Variables Static variables are also known as Class variables.  These variables are declared similarly as instance variables. The difference is that static variables are declared using the static keyword within a class outside any method constructor or block. Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create. Static variables are created at the start of program execution and destroyed automatically when execution ends. Initialization of Static Variable is not Mandatory. Its default value is 0 If we access the static variable like the Instance variable (through an object), the compiler will show the warning message, which won’t halt the program. The compiler will replace the object name with the class name automatically. If we access the static variable without the class name, the compiler will automatically append the class name.

Programming Toolkit - Variables Differences between the Instance variable Vs. the Static variables Each object will have its copy of the instance variable, whereas We can only have one copy of a static variable per class irrespective of how many objects we create. Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of the instance variable. In the case of static, changes will be reflected in other objects as static variables are common to all objects of a class. We can access instance variables through object references, and Static Variables can be accessed directly using the class name .

Programming Toolkit – Data Types Data Types Primitive Data Types are only single values and have no special capabilities.  The  Non-Primitive or Reference Data Types  will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. Used to represent the type of memory allocation. Used with variables and methods. These are fixed.

Programming Toolkit-Operators Operators Arithmetic Operators Unary Operators Assignment Operator Relational Operators Logical Operators Ternary Operator Bitwise Operators Shift Operators instance of operator Precedence and Associativity

Introduction to control constructs Control Structures Loops - Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For -   For loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. For each - For-each is another array traversing technique like for loop, while loop, do-while loop  Do while - D o while loop is like to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of  Exit Control Loop While - A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

Introduction to control constructs Control Structures Condition statements (Decision Making) If If –Else Switch Condition statements (Decision Making) Break Jump Continue

Programming – Languages and Frameworks Programming Toolkit Languages C, C++, C#.NET, ASP.NET JAVA Python, Angular, React JS Java Script Type Script Node JS Programming frameworks Visual Studio .NET Visual Studio Code - Angular, React, .NET, Java, IntelliJ – Java Android Studio Django SQL Management Studio Oracle

Function_name   It is the unique name of that function.   It is always recommended to declare a function before it is used.  Parameters    A function can take some parameters as inputs. These parameters are specified  along with their data types.  For eg - if we are writing a function to add 2 integers, the parameters would be  passed like –  int add (int num1, int num2). Main function    The main function is a special function as the computer starts running the code  from the beginning of the main function. Main function serves as the entry  point for the program. The syntax for function declaration is : return-type function_name (parameter 1, parameter2,  …… parameter n) {  // function_body   }  return-type   The return type of a function is the data type of the variable that that function  returns.   Programming – Function & Methods - A function is a block of code that performs a specific task.  - Why are functions used?  If some functionality is performed at multiple places in software, then  rather than writing the same code, again and again, we create a function  and call it everywhere. This helps reduce code redundancy.  Functions make maintenance of code easy as we must change at one  place if we make future changes to the functionality.  Functions make the code more readable and easier to understand. 

Programming – Constructors Constructor : A constructor is a method used to initialize the state of an object Constructor is a special method which is invoked automatically at the time of object creation. Constructors have the same name as class or structure.  Constructors don’t have a return type. (Not even void) Constructors are only called once, at object creation. There can be three types of constructors in Java.  1. Non-Parameterized constructor : A constructor which has no argument is known as non-parameterized constructor(or no-argument constructor). It is invoked at the time of creating an object. If we don’t create one then it is created by default by Java. 2. Parameterized constructor : Constructor which has parameters is called a parameterized constructor. It is used to provide different values to distinct objects. 3. Copy Constructor : A Copy constructor is an overloaded  constructor used to declare and initialize an object from another object. There is only a user defined copy constructor in Java(C++ has a default one too). In short, we use the constructor to  initialize the instance variable of the class.

Java – Constructor vs methods Constructors Methods A Constructor is a block of code that initializes a newly created object. A Method is a collection of statements which returns a value upon its execution. A Constructor can be used to initialize an object. A Method consists of Java code to be executed. A Constructor is invoked implicitly by the system. A Method is invoked by the programmer. A Constructor is invoked when a object is created using the keyword  new . A Method is invoked through method calls. A Constructor doesn’t have a return type. A Method must have a return type. A Constructor initializes a object that doesn’t exist. A Method does operations on an already created object. A Constructor’s name must be same as the name of the class. A Method’s name can be anything. A class can have many Constructors but must not have the same parameters. A class can have many methods but must not have the same parameters. A Constructor cannot be inherited by subclasses. A Method can be inherited by subclasses.

OOPS – Object Oriented Programming System

Java Keywords

Keyword List List of Useful Keywords along with the description

The Java new keyword is used to create an instance of the class. In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory. We can also use the new keyword to create the array object. Points to remember It is used to create the object. It allocates the memory at runtime. All objects occupy memory in the heap area. It invokes the object constructor. It requires a single, postfix argument to call the constructor Keywords – New

Java return keyword is used to complete the execution of a method. The return followed by the appropriate value that is returned to the caller. This value depends on the method return type like int method always return an integer value. Points to remember It is used to exit from the method. It is not allowed to use return keyword in void method. The value passed with return keyword must match with return type of the method. Keywords – Return

There can be a lot of usage of  Java this keyword . In Java, this is a  reference variable  that refers to the current object. Usage of Java this keyword Here is given the 6 usage of java this keyword. this can be used to refer current class instance variable this can be used to invoke current class method (implicitly) this() can be used to invoke current class constructor. this can be passed as an argument in the method call. this can be passed as argument in the constructor call. this can be used to return the current class instance from the method. U se this keyword to distinguish local variable and instance variable. Keywords – This

Keywords – Super The  super  keyword in Java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. The keyword “super” came into the picture with the concept of Inheritance. Usage of Java super Keyword Use of super with variables:  This scenario occurs when a derived class and base class has same data members. In that case there is a possibility of ambiguity for the JVM.  2.Use of super with methods:  This is used when we want to call parent class method. So, whenever a parent and child class have same named methods then to resolve ambiguity, we use super keyword. 3 .  Use of super with constructors:  super keyword can also be used to access the parent class constructor. One more important thing is that ‘’super’ can call both parametric as well as non-parametric constructors depending upon the situation.

Keywords – Final Final  keyword is used in different contexts. First of all,  final  is a  non-access modifier  applicable  only to a variable, a method or a class . Following are different contexts where final is used. Final Variables When a variable is declared with  final  keyword, its value can’t be modified, essentially, a constant. This also means that you must initialize a final variable. If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but the internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from the  final array  or final collection. It is good practice to represent final variables in all uppercase, using underscore to separate words. Final variables do not occupy memory on per-instance basis. All the objects of the classes share the same copy of the final variable. The method declared as final can not be overridden by the subclass of that class in which final method is declared. When a class is declared as final other class can not inherit that final class. Observation 1:  When to use a final variable - Hence final variables must be used only for the values that we want to remain constant throughout the execution of the program. Observation 2:  Reference final variable?  When a final variable is a reference to an object, then this final variable is called the reference final variable.

Definition of Static Static is a keyword, applicable to the classes, variables, methods, and blocks. The class members, class, and blocks can be made static using “static” keyword in front of the name of the class members, class, and blocks respectively. When a class member is declared as static, it becomes global for all other members of the class. The static member of the class does not occupy memory on per instance basis, i.e. all the objects shares the same copy of static member. The static member can be used independently of any object of that class. You can access the static member of the class before its object is created . The best example of the static member is main( ) method, it is declared static so that it can be invoked before any object exists. Static variables A static variable acts like a global variable for all other data members of the class. A static variable can be accessed before any object of the class exists. A static variable can be accessed with the class name in which it is defined followed by the dot(.) operator. Static Methods A static method can only call other static methods only. A static method can access static data only. A static method can not be referred to “this” or “super” in any conditions. A static method can be accessed with the class name in which it is defined followed by the dot(.) operator. Static class Java does have the concept of nested static class. The outermost class can not be made static whereas the innermost class can be made static. A static nested class can not access the non-static member of the outer class. It can only access the static members of the outer class. Static Block Static block is executed only once when the class is loaded. Used to initialize the static variables of the class. Keywords – Static

BASIS FOR COMPARISON STATIC FINAL Applicable Static keyword is applicable to nested static class, variables, methods and block. Final keyword is applicable to class, methods and variables. Initialization It is not compulsory to initialize the static variable at the time of its declaration. It is compulsory to initialize the final variable at the time of its declaration. Modification The static variable can be reinitialized. The final variable can not be reinitialized. Methods Static methods can only access the static members of the class and can only be called by other static methods. Final methods can not be inherited. Class Static class's object can not be created, and it only contains static members only. A final class can not be inherited by any class. Block Static block is used to initialize the static variables. Final keyword supports no such block. The main difference between a static and final keyword is that  static  is keyword is used to define the class member that can be used independently of any object of that class.  Final  keyword is used to declare, a constant variable, a method which can not be overridden and a class that can not be inherited. Static vs Final

Keywords – @Override Annotation Introduction The override annotation type is a marker annotation type. It can only be used on methods. A method annotated with this annotation overrides a method declared in its supertype. If the annotated method does not override a method in the supertype, the compiler will generate an error. Example In the following code, Class B inherits from class A. The m1() method in the class B overrides the m1() method in its superclass A. The annotation @Override on the m1() method in class B tells about this intention. The compiler verifies this statement and finds it to be true in this case. class A { public void m1() { } } class B extends A { @ Override public void m1() { } } The following C class won't compile because m2() does not override any method. class C extends A { @ Override public void m2() { } } The method m2() is a new method declaration in class C.

Programming – Classes & Objects Class A class is a group of objects which have common properties. It is the blueprint/plan/template that describes the details of an object. Before we create an object, we first need to define the class. It is a logical entity. It can't be physical. Object An object is an instance of a class. It has its own state, behavior, and identity. The object of a class can be created by using the new keyword in Java Programming language. An object in Java is the physical as well as a logical entity State : represents the data (value) of an object. Behavior : represents the behavior (functionality) of an object such as deposit, withdraw, etc. Identity : An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.

Programming – Classes & Objects Object Oriented Programming Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior. This approach to programming is well-suited for programs that are large, complex and actively updated or maintained. This includes programs for manufacturing and design, as well as mobile applications. This is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts defined below :

Programming – OOPS OOPs Concepts are as follows:  Class Objec t Method and  method passing Pillars of OOPS Abstraction Encapsulation Inheritance Polymorphism Compile-time polymorphism Run-time polymorphism

Programming – OOPS - Polymorphism Polymorphism -  Polymorphism is the process that allows us to perform a single action in multiple ways. Polymorphism is the ability of a programming language to present the same interface for several different underlying data types In Java polymorphism is mainly divided into two types:  Compile-time Polymorphism (Method – Overloading) Runtime Polymorphism (Method – Overriding) ( polymorphism Rules - Return type, Parameter Type, No of Arg either of this has to be unique)

Polymorphism – Overloading & Overriding Methods Method Overloading Method Overriding Method overloading is a compile-time polymorphism. Method overriding is a run-time polymorphism. It helps to increase the readability of the program. It is used to grant the specific implementation of the method which is already provided by its parent class or superclass. It occurs within the class. It is performed in two classes with inheritance relationships. Method overloading may or may not require inheritance. Method overriding always needs inheritance. In method overloading, methods must have the same name and different signatures. In method overriding, methods must have the same name and same signature. In method overloading, the return type can or can not be the same, but we just have to change the parameter. In method overriding, the return type must be the same or co-variant.

Polymorphism – Overloading & Overriding Methods Method Overloading : Method Overloading is a  Compile time polymorphism . In method overloading, more than one method shares the same method name with a different signature in the class. In method overloading, the return type can or can not be the same, but we have to change the parameter because, in java, we can not achieve the method overloading by changing only the return type of the method.  Method Overriding :  Method Overriding is a  Run time polymorphism . In method overriding, the derived class provides the specific implementation of the method that is already provided by the base class or parent class. In method overriding, the return type must be the same or co-variant (return type may vary in the same direction as the derived class).  the method Overriding is bound to the instances on the run time, which is decided by the  JVM . That’s why it is called  Run time polymorphism.

Is A and Has A Relationship A relationship  in Java means different relations between two or more classes. For example, if a class Bulb inherits another class Device, then we can say that Bulb is having is-a relationship with Device, which implies Bulb is a device.   In Java, we have two types of relationship: Is-A relationship:  Whenever one class inherits another class, it is called an IS-A relationship. Has-A relationship:  Whenever an instance of one class is used in another class, it is called HAS-A relationship.

Association Composition and Aggregation  Association is a relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object.  Composition  and  Aggregation  are the two forms of association. 

Polymorphism – Overloading & Overriding Methods Composition Composition  is a “belongs-to” type of relationship. It means that one of the objects is a logically larger structure, which contains the other object. In other words, it's part or member of the other object. Alternatively,  we often call it a “has-a” relationship  (as opposed to an “is-a” relationship, which is  inheritance ). For example, a room belongs to a building, or in other words a building has a room. So basically, whether we call it “belongs-to” or “has-a” is only a matter of point of view. Aggregation Aggregation is also a “has-a” relationship. What distinguishes it from composition, that it doesn't involve owning. As a result, the lifecycles of the objects aren't tied: every one of them can exist independently of each other. For example, a car and its wheels.  We can take off the wheels, and they'll still exist.  We can mount other (preexisting) wheels, or install these to another car and everything will work just fine. Association Association is the weakest relationship between the three.  It isn't a “has-a” relationship , none of the objects are parts or members of another. Association only means that the objects “know” each other.  For example, a mother and her child.

Programming – OOPS - Inheritance Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class.  Let us discuss some of frequent used important terminologies: Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class). Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. Types of Inheritance in Java Single Inheritance Multi Level Inheritance Hierarchical  Inheritance Hybrid Inheritance Multiple Inheritance (Through Interfaces)

Programming – OOPS- Abstraction Abstraction Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects. Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.   In java, abstraction is achieved by  interfaces  and  abstract classes . We can achieve 100% abstraction using interfaces.

Programming – OOPS- Abstraction Encapsulation vs Data Abstraction Encapsulation  is data hiding(information hiding) while Abstraction is detailed hiding(implementation hiding). While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing the interface to the user and hiding the details of implementation. Advantages of Abstraction It reduces the complexity of viewing the things. Avoids code duplication and increases reusability. Helps to increase the security of an application or program as only important details are provided to the user.

Programming – OOPS - Encapsulation Encapsulation - It is defined as the wrapping up of code and data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.  Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared. The meaning of  Encapsulation , is to make sure that "sensitive" data is hidden from users. To achieve this, you must: declare class variables/attributes as  private provide public  get  and  set  methods to access and update the value of a  private  variable Advantage of Encapsulation in Java By providing only a setter or getter method, you can make the class  read-only or write-only . In other words, you can skip the getter or setter methods. It provides you the  control over the data . It is a way to achieve  data hiding  in Java because other class will not be able to access the data through the private data members. The encapsulate class is  easy to test . So, it is better for unit testing.

Programming – OOPS - Encapsulation Why Encapsulation? Better control of class attributes and methods Class attributes can be made  read-only  (if you only use the  get  method), or  write-only  (if you only use the  set  method) Flexible: the programmer can change one part of the code without affecting other parts Increased security of data

Getter and Setter methods You learned that  private  variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public  get  and  set  methods. The  get  method returns the variable value, and the  set  method sets the value. Set Method  /  Setter method in java: Purpose of Setter method is to set new value or assign new value to instance variable . Method name should follow naming convention setVARIABLENAME (). It should accept some value as an argument. here method argument should be of type of variable. It should have a statement to assign argument value to corresponding variable. It does not have any return type. void should be the method return type. In order to set some value to variable we need to call corresponding setter method  by passing required value. Get method / Getter  method in java: Purpose of Getter method is to get the value of the instance variable. Method name should follow naming convention getVARIABLENAME (). It should not have any arguments. It should return corresponding variable value. So return type must be of type of variable we are returning from the method. In order to get the variable value we need to call corresponding getter method of variable.

Programming – Package Package in Java Package is a group of similar types of classes, interfaces and sub-packages. (Carton - Related Items/code – buttons, look, data handle of web side) Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt , javax , swing, net, io, util, sql etc. Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision.

Access Identifier What are the different access specifiers for Java classes? There are two types of modifiers in Java:  access modifiers  and  non-access modifiers . The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. Private : The access level of a private modifier is only within the class. It cannot be accessed from outside the class. Default : The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. Protected : The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. Public : The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.

Access Identifier Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y

Java – Garbage Collection Garbage Collection Garbage Collection is the mechanism provided by JVM, to clean out the Heap, so that new objects can be created. It destroys the objects which are “not in use” or eligible for “garbage collection”. Any object is said to be eligible for garbage collection (GC) if there is no “Reference Variable” attached to it.

Java – Interface An  Interface in Java  programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a class. A Java interface contains static constants and abstract methods. The interface in Java is  a  mechanism to achieve  abstraction . There can be only abstract methods in the Java interface, not the method body. It is used to achieve abstraction and  multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also  represents the IS-A relationship . Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).  Interfaces specify what a class must do and not how. It is the blueprint of the class. An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So, it specifies a set of methods that the class has to implement. 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. A Java library example is  Comparator Interface. If a class implements this interface, then it can be used to sort a collection.

Java – Class vs Interface Class Interface The keyword used to create a class is “class” The keyword used to create an interface is “interface” A class can be instantiated i.e, objects of a class can be created. An Interface cannot be instantiated i.e, objects cannot be created. Classes does not support multiple inheritance. Interface supports multiple inheritance. It can be inherit another class. It cannot inherit a class. It can be inherited by another class using the keyword ‘extends’. It can be inherited by a class by using the keyword ‘implements’ and it can be inherited by an interface using the keyword ‘extends’. It can contain constructors. It cannot contain constructors. It cannot contain abstract methods. It contains abstract methods only. Variables and methods in a class can be declared using any access specifier(public, private, default, protected) All variables and methods in a interface are declared as public. Variables in a class can be static, final or neither. All variables are static and final.  

Collection Framework

Collection Framework - Introduction The  Collection in Java  is a framework that provides an architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion. Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (Array List, Vector, LinkedList, Priority Queue, HashSet, Linked HashSet, Tree Set). What is Collection in Java A Collection represents a single unit of objects, i.e., a group. What is a framework in Java It provides readymade architecture. It represents a set of classes and interfaces. It is optional. What is Collection framework The Collection framework is a set of classes and interfaces that implement commonly reusable data structures. It represents a unified architecture for storing and manipulating a group of objects. It has: Interfaces and its implementations, i.e., classes

Collection Framework - Hierarchy

Collection Framework – Iterators & List Iterator interface provides the facility of iterating the elements in a forward direction only. Iterable Interface The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface List Interface List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store the ordered collection of objects. It can have duplicate values. List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack. To instantiate the List interface, we must use : List <data-type> list1=  new  ArrayList();   List <data-type> list2 =  new  LinkedList();   List <data-type> list3 =  new  Vector();   List <data-type> list4 =  new  Stack();  

Collection Framework – Link vs Set vs Map List Set Map The list interface allows duplicate elements Set does not allow duplicate elements. The map does not allow duplicate elements The list maintains insertion order. Set do not maintain any insertion order.  The map also does not maintain any insertion order.  We can add any number of null values. But in set almost only one null value. The map allows a single null key at most and any number of null values. List implementation classes are  Array List ,  LinkedList . Set implementation classes are  HashSet,   LinkedHashSet , and  Tree Set .  Map implementation classes are  HashMap ,  HashTable ,  TreeMap ,  ConcurrentHashMap , and  LinkedHashMap . The list provides get() method to get the element at a specified index. Set does not provide get method to get the elements at a specified index The map does not  provide get method to get the elements at a specified index If you need to access the elements frequently by using the index, then we can use the list If you want to create a collection of unique elements, then we can use set If you want to store the data in the form of key/value pair, then we can use the map. To traverse the list elements by using Listlterator. Iterator can be used traverse the set elements Through keyset, value, and entry set.

Collection Framework – Array List ArrayList is a part of  collection framework  and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays, but  it is much more flexible than the traditional array and can be helpful in programs where lots of manipulation in the array is needed. This class is found in  java.util package.  ArrayList maintains the insertion order internally. ArrayList inherits Abstract List class and implements the List interface. ArrayList is initialized by the size. However, the size is increased automatically if the collection grows or shrinks if the  objects  are removed from the collection. Java ArrayList allows us to randomly access the list. ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases. ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.

Collection Framework – Linked List Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the Abstract List class and implements List and Deque interfaces. The important points about Java LinkedList are: Java LinkedList class can contain duplicate elements. Java LinkedList class maintains insertion order. Java LinkedList class is non synchronized. In Java LinkedList class, manipulation is fast because no shifting needs to occur. Java LinkedList class can be used as a list, stack or queue.

Collection Framework – Vector Java Vector Vector  is like the  dynamic array  which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in the  java.util  package and implements the  List  interface, so we can use all the methods of List interface here. It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in such case. The Iterators returned by the Vector class are  fail-fast . In case of concurrent modification, it fails and throws the ConcurrentModificationException . It is similar to the ArrayList, but with two differences- Vector is synchronized. Java Vector contains many legacy methods that are not the part of a collection framework.

ArrayList vs Linked List ArrayList LinkedList 1) ArrayList internally uses a  dynamic array  to store the elements. LinkedList internally uses a  doubly linked list  to store the elements. 2) Manipulation with ArrayList is  slow  because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is  faster  than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. 3) An ArrayList class can  act as a list  only because it implements List only. LinkedList class can  act as a list and queue  both because it implements List and Deque interfaces. 4) ArrayList is  better for storing and accessing  data. LinkedList is  better for manipulating  data.

ArrayList Vs Vector ArrayList Vector 1) ArrayList is  not synchronized . Vector is  synchronized . 2) ArrayList  increments 50%  of current array size if the number of elements exceeds from its capacity. Vector  increments 100%  means doubles the array size if the total number of elements exceeds than its capacity. 3) ArrayList is  not a legacy  class. It is introduced in JDK 1.2. Vector is a  legacy  class. 4) ArrayList is  fast  because it is non-synchronized. Vector is  slow  because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object. 5) ArrayList uses the  Iterator  interface to traverse the elements. A Vector can use the  Iterator  interface or  Enumeration  interface to traverse the elements.

Collection Framework – Stack The  stack  is a linear data structure that is used to store the collection of objects. It is based on  Last-In-First-Out  (LIFO).  Java collection  framework provides many interfaces and classes to store the collection of objects. One of them is the  Stack class  that provides different operations such as push, pop, search, etc. In this section, we will discuss the  Java Stack class , its  methods,  and  implement  the stack data structure in a  Java program . But before moving to the Java Stack class have a quick view of how the stack works. The stack data structure has the two most important operations that are  push  and  pop . The push operation inserts an element into the stack and pop operation removes an element from the top of the stack. Let's see how they work on stack.

Collection Framework – Queue The Queue interface present in the  java.util  package and extends the  Collection interface  is used to hold the elements about to be processed in FIFO(First In First Out) order. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of the list, (i.e.), it follows the FIFO or the First-In-First-Out principle. Since  Queue  is an  interface , objects cannot be created of the type queue. We always need a class which extends this list in order to create an object. The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO manner. It inherits AbstractQueue class. A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a  Queue  follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.  

Collection Framework – Queue Method Description boolean add(object) It is used to insert the specified element into this queue and return true upon success. boolean offer(object) It is used to insert the specified element into this queue. Object remove() It is used to retrieves and removes the head of this queue. Object poll() It is used to retrieves and removes the head of this queue, or returns null if this queue is empty. Object element() It is used to retrieves, but does not remove, the head of this queue. Object peek() It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

Collection Framework – Array deque The  ArrayDeque in Java  provides a way to apply resizable-array in addition to the implementation of the Deque interface. It is also known as  Array Double Ended Queue  or  Array Deck . This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue.  Few  important features  of ArrayDeque are as follows:   Array deques have no capacity restrictions and they grow as necessary to support usage. They are not thread-safe which means that in the absence of external synchronization, ArrayDeque does not support concurrent access by multiple threads. Null elements are prohibited in the ArrayDeque . ArrayDeque class is likely to be faster than Stack when used as a stack. ArrayDeque class is likely to be faster than LinkedList when used as a queue.

Collection Framework – Hash Set Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface. The important points about Java HashSet class are: HashSet stores the elements by using a mechanism called hashing. HashSet contains unique elements only. HashSet allows null value. HashSet class is non synchronized. HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode . HashSet is the best approach for search operations. The initial default capacity of HashSet is 16, and the load factor is 0.75. Difference between List and Set A list can contain duplicate elements whereas Set contains unique elements only.

Collection Framework – Linked Hash Set Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface. The important points about Java LinkedHashSet class are: Java LinkedHashSet class contains unique elements only like HashSet. Java LinkedHashSet class provides all optional set operation and permits null elements. Java LinkedHashSet class is non synchronized. Java LinkedHashSet class maintains insertion order.

Collection Framework – Tree Set Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order. The important points about Java TreeSet class are: Java TreeSet class contains unique elements only like HashSet. Java TreeSet class access and retrieval times are quiet fast. Java TreeSet class doesn't allow null element. Java TreeSet class is non synchronized. Java TreeSet class maintains ascending order.

Collection Framework – Hash Table Java Hashtable class implements a hashtable , which maps keys to values. It inherits Dictionary class and implements the Map interface. Points to remember A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode () method. A Hashtable contains values based on the key. Java Hashtable class contains unique elements. Java Hashtable class doesn't allow null key or value. Java Hashtable class is synchronized. The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75. Hashtable class Parameters Let's see the Parameters for java.util.Hashtable class. K : It is the type of keys maintained by this map. V : It is the type of mapped values.

Collection Framework – Hash Map Java  HashMap  class implements the Map interface which allows us  to store key and value pair , where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updating, deletion, etc. HashMap class is found in the  java.util  package. HashMap in Java is like the legacy Hash table class, but it is not synchronized. It allows us to store the null elements as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the Abstract Map class and implements the Map interface. Points to remember Java HashMap contains values based on the key. Java HashMap contains only unique keys. Java HashMap may have one null key and multiple null values. Java HashMap is non synchronized. Java HashMap maintains no order. The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Collection Framework – Linked Hash Map Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface. Points to remember Java LinkedHashMap contains values based on the key. Java LinkedHashMap contains unique elements. Java LinkedHashMap may have one null key and multiple null values. Java LinkedHashMap is non synchronized. Java LinkedHashMap maintains insertion order. The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Collection Framework – Tree Map Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order. The important points about Java TreeMap class are: Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. Java TreeMap contains only unique elements. Java TreeMap cannot have a null key but can have multiple null values. Java TreeMap is non synchronized. Java TreeMap maintains ascending order. HashMap TreeMap 1) HashMap can contain one null key. TreeMap cannot contain any null key. 2) HashMap maintains no order. TreeMap maintains ascending order. What is difference between HashMap and TreeMap ?

HashMap Hashtable 1) HashMap is  non synchronized . It is not-thread safe and can't be shared between many threads without proper synchronization code. Hashtable is  synchronized . It is thread-safe and can be shared with many threads. 2) HashMap  allows one null key and multiple null values . Hashtable   doesn't allow any null key or value . 3) HashMap is a  new class introduced in JDK 1.2 . Hashtable is a  legacy class . 4) HashMap is  fast . Hashtable is  slow . 5) We can make the HashMap as synchronized by calling this code Map m = Collections.synchronizedMap ( hashMap ); Hashtable is internally synchronized and can't be unsynchronized. 6) HashMap is  traversed by Iterator . Hashtable is  traversed by Enumerator and Iterator . 7) Iterator in HashMap is  fail-fast . Enumerator in Hashtable is  not fail-fast . 8) HashMap inherits  AbstractMap  class. Hashtable inherits  Dictionary  class. Hash Map vs Hash Table

Exception Handling

Exception Handling The  Exception Handling in Java  is one of the powerful  mechanism to handle the runtime errors  so that the normal flow of the application can be maintained. In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and unchecked exceptions. What is Exception in Java? Dictionary Meaning:  Exception is an abnormal condition. In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. What is Exception Handling? Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException , IOException , SQLException , RemoteException , etc. Advantage of Exception Handling The core advantage of exception handling is  to maintain the normal flow of the application . An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions

Exception Handling The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error.

Exception Handling - Types Types of Java Exceptions There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely: 1) Checked Exception The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException , SQLException , etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException , NullPointerException , ArrayIndexOutOfBoundsException , etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. 3) Error Error is irrecoverable. Some example of errors are OutOfMemoryError , VirtualMachineError , AssertionError etc.

Exception Handling – Throw and Throws Throw - The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either  checked or unchecked exception . The throw keyword is mainly used to throw custom exceptions.  Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions. Throws - T hrows is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.  To prevent this compile time error we can handle the exception in two ways:  By using  try catch By using  throws  keyword We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.   Important points to remember about throws keyword:   throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless. throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program. By the help of throws keyword, we can provide information to the caller of the method about the exception.

Exception Handling – Try with resources In Java, the try-with-resources statement is a try statement that declares one or more resources. The resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures that each resource is closed at the end of the statement execution. You can pass any object that implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable . declaring and instantiating the resource within the try clause. specifying and handling all exceptions that might be thrown while closing the resource. try (resource declaration) { // use of the resource } catch ( ExceptionType e1) { // catch block }

Exception Handling – User Defined Exceptions An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating our own Exception is known as a custom exception or user-defined exception. Why use custom exceptions? Java exceptions cover almost all the general types of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions. Following are a few of the reasons to use custom exceptions: To catch and provide specific treatment to a subset of existing Java exceptions. Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem. In order to create a custom exception, we need to extend the Exception class that belongs to  java.lang package.

Wrapper Classes A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Need of Wrapper Classes They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value). The classes in java.util package handles only objects and hence wrapper classes help in this case also. Data structures in the Collection framework, such as  ArrayList  and  Vector , store only objects (reference types) and not primitive types. An object is needed to support synchronization in multithreading. Autoboxing:  Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.   // Java program to demonstrate Autoboxing    import java.util.ArrayList ; class Autoboxing {      public static void main(String[] args ){          char ch = 'a' ;             // Autoboxing- primitive to Character object conversion          Character a = ch ;             ArrayList<Integer> arrayList = new ArrayList<Integer>();             // Autoboxing because ArrayList stores only objects          arrayList.add ( 25 );             // printing the values from object          System.out.println ( arrayList.get ( ));}}

Scanner Class Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file. To read numerical values of a certain data type XYZ, the function to use is nextXYZ (). For example, to read a value of type short, we can use nextShort () To read strings, we use nextLine (). To read a single character, we use next(). charAt (0). next() function returns the next token/word in the input as a string and charAt (0) function returns the first character in that string.

Type Casting In Java,  type casting  is a method or process that converts a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer.  Widening Type Casting Converting a lower data type into a higher one is called  widening  type casting. It is also known as  implicit conversion  or  casting down . It is done automatically. It is safe because there is no chance to lose data.   It takes place when: Both data types must be compatible with each other. The target type must be larger than the source type. byte  ->  short  ->  char  ->  int  ->  long  ->  float  ->  double Narrowing Type Casting Converting a higher data type into a lower one is called  narrowing  type casting. It is also known as  explicit conversion  or  casting up . It is done manually by the programmer. If we do not perform casting then the compiler reports a compile-time error. double  ->  float  ->  long  ->  int  ->  char  ->  short  ->  byte

String S tring is basically an object that represents sequence of char values. An  Array of characters works same as Java string. For example: Java String  class provides a lot of methods to perform operations on strings such as compare(), concat (), equals(), split(), length(), replace(), compareTo (), intern(), substring() etc. The java.lang.String class implements  Serializable ,  Comparable  and  CharSequence   interfaces The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes. There are two ways to create String object: By string literal String s1= "Welcome" ;   String s2= "Welcome" ; //It doesn't create a new instance    char   ch []={ 's' , 't' , 'r' , ' i ' , ' n' , 'g' , 's ' };     2. By new keyword String s= new  String( "Welcome" ); //creates two objects and one reference variable   

Programming – Ternary Operator Ternary Operator The ternary operator or ?, is a shorthand if else statement. It can be used to evaluate an expression and return one of two operands depending on the result of the expression. booleanb = true;String s = ( b == true ? "True" : "False" ); Or the above can be written as booleanb = true;String s;if (b == true){s = "True";}else{s = "False";}

Regular Expression Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under  java.util.regex  package. Java does not have a built-in Regular Expression class, but we can import the  java.util.regex  package to work with regular expressions. This consists of  3 classes and 1 interface. : Pattern Class - Defines a pattern (to be used in a search) Matcher Class - Used to search for the pattern PatternSyntaxException  Class - Indicates syntax error in a regular expression pattern MatchResult Interface - Used for representing the result of a match operation A regular expression can be a single character, or a more complicated pattern. Regular expressions can be used to perform all types of  text search  and  text replace  operations. F lags Flags in the compile() method change how the search is performed. Here are a few of them: Pattern.CASE_INSENSITIVE  - The case of letters will be ignored when performing a search. Pattern.LITERAL  - Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search. Pattern.UNICODE_CASE  - Use it together with the CASE_INSENSITIVE flag to also ignore the case of letters outside of the English alphabet

Regular Expression Patterns Expression Description [abc] Find one character from the options between the brackets [^ abc ] Find one character NOT between the brackets [0-9] Find one character from the range 0 to 9 Metacharacter Description | Find a match for any one of the patterns separated by | as in: cat|dog|fish . Find just one instance of any character ^ Finds a match as the beginning of a string as in: ^Hello $ Finds a match at the end of the string as in: World$ \d Find a digit \s Find a whitespace character \b Find a match at the beginning of a word like this: \ bWORD , or at the end of a word like this: WORD\b \uxxxx Find the Unicode character specified by the hexadecimal number xxxx Metacharacters are characters with a special meaning: The first parameter of the  Pattern.compile ()  method is the pattern. It describes what is being searched for. Brackets are used to find a range of characters:

Regular Expression Patterns Quantifier Description n+ Matches any string that contains at least one  n n* Matches any string that contains zero or more occurrences of  n n? Matches any string that contains zero or one occurrences of  n n{x} Matches any string that contains a sequence of  X   n 's n{x,y} Matches any string that contains a sequence of X to Y  n 's n{x,} Matches any string that contains a sequence of at least X  n 's Quantifiers define quantities: Note:  If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape them. In Java, backslashes in strings need to be escaped themselves, so two backslashes are needed to escape special characters. For example, to search for one or more question marks you can use the following expression: "\\?"

File I/O File Handling

File I/O Java I/O  (Input and Output) is used  to process the input  and  produce the output . Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations. We can perform  file handling in Java  by Java I/O API. Stream A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. In Java, 3 streams are created for us automatically. All these streams are attached with the console. 1) System.out :  standard output stream 2) System.in:  standard input stream 3) System.err :  standard error stream File Handling in Java File handling is a crucial part of any programming language. In Java, file handling is done with the help of the File class of the java.io package. Common file handling operations : Creating a new file. Writing in a file. Reading an existing file. Deleting a file.

File Handling in Java What is File I/O? Java I/O stream is the flow of data that you can either read from, or you can write to. It is used to perform read and write operations in file permanently. Java uses streams to perform these tasks.  Java I/O stream  is also called  File Handling , or  File I/O.  It is available in  java.io  package. Java.io package provides classes for system input and output through files, network streams, memory buffers, etc.

File Handling in Java Some input-output stream will be initialized automatically by the JVM and these streams are available in System class as  in ,  out , and  err  variable. In  reference refers to the default input device, i.e. keyboard. Out  and  err  refers to the default output device, i.e. console. Streams: Streams are the sequence of bits(data). There are two types of streams: Input Streams: Input streams are used to read the data from various input devices like keyboard, file, network, etc. Output Streams: Output streams are used to write the data to various output devices like monitor, file, network, etc.

Java Sample Programs

How are Java objects stored in memory? In Java, all objects are dynamically allocated on Heap. In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on heap For example, following program fails in the compilation. Compiler gives error  “Error here because t is not initialized”.

The java.lang.reflect.Array.set () is an inbuilt method in Java and is used to set a specified value to a specified index of a given object array. Parameter : array :  This is an array of type Object which is to be updated. index :  This is the index of the array which is to be updated. value :  This is the value that is to be set at the given  index  of the given  array Return type :  This is a void type method this doesn’t returns any value. The update reflects upon the Object array passed as the argument. Exception :  This method throws following exception. NullPointerException   – when the array is null. IllegalArgumentException  – when the given object array is not an Array. ArrayIndexOutOfBoundsException  – if the given index is not in the range of the size of the array. Array Set Method