Object Oriented Programming Object means a real-world entity such as a pen, chair, table, computer, watch, etc. ObjectOriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: Object Classes Inheritance Polymorphism Abstraction Encapsulation Classes and Objects Object Any entity that has state and behavior is known as an object. For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc. Class A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Core properties include the data types and methods that may be used by the object A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space. Advantages of OOPs over Procedure Oriented Programming OOPs makes development and maintenance easier whereas in a procedure-oriented programming language it is not easy to manage if code grows as project size increases. OOPs provides data hiding whereas in a procedure-oriented programming language a global data can be accessed from anywhere. public class Dog { String breed; int age; String color; void barking() { } void hungry() { } void sleeping() { } } A class is a blueprint from which individual objects are created. The code above is a sample of a class Dog with attributes and behavior. Constructors Constructor In Java, a constructor is a block of codes similar to the method. It is called when an instance of the object is created, and memory is allocated for the object. It is a special type of method which is used to initialize the object. When is a constructor called? When an object is created, compiler makes sure that constructors for all of its subobjects (its member and inherited objects) are called. If members have default constructors or constructor without parameter then these constructors are called automatically, otherwise parameterized constructors can be called using initializer list. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any. Rules to remember while creating a constructor There are three rules defined for the constructor. Constructor name must be the same as its class name A Constructor must have no explicit return type A Java constructor cannot be abstract, static, final, and synchronized Types of constructors Default Constructor Parameterized Constructor Default Constructor The default constructor is a no-args constructor that the Java compiler inserts on your behalf; it contains a default call to super(); which is the default behavior. If you implement any constructor then you no longer receive a default constructor. Note : If there is no constructor in the class, the compiler adds a default constructor No-Argument Constructor public Bicycle() { gear = 1; cadence = 10; speed = 0; } Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike. Note : The diagram below describes that a default constructor is added by the compiler when there is no constructor declared in the class. Parameterized Constructor A constructor which has a specific number of parameters is called a parameterized constructor. The parameterized constructor is used to provide different values to the distinct objects. However, you can provide the same values also. class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } In the above example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. Constructor Overloading In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. class Student5{ int id; String name; int age; //creating two argument constructor Student5(int i,String n){ id = i; name = n; } //creating three argument constructor Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } } Constructor vs Method Constructor : A constructor is used to initialize the state of an object. A constructor must not have a return type. The constructor is invoked implicitly. The Java compiler provides a default constructor if you don't have any constructor in a class. The constructor name must be same as the class name. Method : A method is used to expose the behavior of an object. A method must have a return type. The method is invoked explicitly. The method is not provided by the compiler in any case. The method name may or may not be same as class name. OOP Pillars Object Oriented Programming Pillars Inheritance Polymorphism Encapsulation Abstraction We will look at all the four pillars in more detail. Inheritance Inheritance Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Advantages of Inheritance For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Terms used in Inheritance Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. Syntax class Subclass-name extends Superclass-name { //methods and fields added here } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. Example of Inheritance As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Types Of Inheritance In Java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later. Single Inheritance class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ //Single Inheritance void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); }} Multilevel Inheritance class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ //Level 1 - Inheritance void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ //Level 2 - Inheritance void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }} Hierarchical Inheritance class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ // Hierarchical Inheritance void bark(){System.out.println("barking...");} } class Cat extends Animal{ // Hierarchical Inheritance void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark(); //Error }} Why multiple inheritance is not supported in Java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{ //suppose if it were public static void main(String args[]){ C obj=new C(); obj.msg(); //Now which msg() method would be invoked? } } Polymorphism Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. Method Overloading If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. Different ways to overload a method? There are two ways to overload the method in java By changing number of arguments By changing the data type Method Overloading - Changing the number of arguments class Adder{ static int add(int a,int b){return a+b;} // 2 arguments static int add(int a,int b,int c){return a+b+c;} //3 arguments } class TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }} In the above example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers. In the above example, we are creating static methods so that we don't need to create instance for calling methods. Method Overloading - Changing data type of arguments class Adder{ static int add(int a, int b){return a+b;} // 2 arguments of int data type static double add(double a, double b){return a+b;} // 2 arguments of double data type } class TestOverloading2{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }} In the above example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments. Note : Method overloading is not possible by changing the return type of the method. Overloading the main() method in Java class TestOverloading4{ public static void main(String[] args){System.out.println("main with String[]");} public static void main(String args){System.out.println("main with String");} public static void main(){System.out.println("main without args");} } Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Method Overriding If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. Usage and Rules for Method Overriding Usage : Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. Method overriding is used for runtime polymorphism Rules : The method must have the same name as in the parent class The method must have the same parameter as in the parent class. There must be an IS-A relationship (inheritance). Example for Method Overriding class ABC{ //Overridden method public void disp() { System.out.println("disp() method of parent class"); } } class Demo extends ABC{ //Overriding method public void disp(){ System.out.println("disp() method of Child class"); } public void newMethod(){ System.out.println("new method of child class"); } public static void main( String args[]) { ABC obj = new ABC(); obj.disp(); ABC obj2 = new Demo(); // Covariance with reference types obj2.disp(); } } In the above example, we have defined the disp() method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter list of the methods are the same, and there is IS-A relationship between the classes. Can a static method be overridden? No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later. It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area. Method Overloading vs Method Overriding Method Overloading : Method overloading is used to increase the readability of the program. Method overloading is performed within class. In case of method overloading, parameter must be different. Method overloading is the example of compile time polymorphism. In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Method Overriding : Method overriding is used to provide the specific implementation of the method that is already provided by its super class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. In case of method overriding, parameter must be same. Method overriding is the example of run time polymorphism. Return type must be same or covariant in method overriding. Sample Exercise Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest. Go ahead and code the above scenario. Encapsulation Encapsulation Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines. We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it. The Java Bean class is the example of a fully encapsulated class. Advantages of Encapsulation 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. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods. 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. Example for Encapsulation package com.revature; public class Student{ //private data member private String name; //getter method for name public String getName(){ return name; } //setter method for name public void setName(String name){ this.name=name } } //A Java class to test the encapsulated class. package com.revature; class Test{ public static void main(String[] args){ //creating instance of the encapsulated class Student s=new Student(); //setting value in the name member s.setName("vijay"); //getting value of the name member System.out.println(s.getName()); } } The above is an example of encapsulation of a class called Student that has only one field with its setter and getter methods. Read-Only Class //A Java class which has only getter methods. public class Student{ //private data member private String college="AKG"; //getter method for college public String getCollege(){ return college; } } The above class is an example of a Read-Only class because it has only a getter to access the college name. If the user tries to change the value of the college name, a compile-time error is rendered. Write-Only Class //A Java class which has only setter methods. public class Student{ //private data member private String college; //getter method for college public void setCollege(String college){ this.college=college; } } The above class is an example of a Write-Only class because it has only setters to change the value of the college name and cannot read the college name. Even if tried to access outside of this class a compile-time error is displayed only because the variable is declared as private. Access Modifiers There are two types of modifiers in java: access modifiers and non-access modifiers. The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. There are 4 types of java access modifiers: private default protected public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers. Access Modifiers with Method Overriding class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ void msg(){System.out.println("Hello java");} // Error because Class Simple method msg() is more restrictive that Class A method msg() public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } } If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive. Sample Exercise Create an encapsulated class with 4 fields and the respective methods to access and edit those fields. Then go ahead and create a test class to verify. Class Name : Student Field Names : studentId, studentName, collegeName, address Test Class Name : TestStudent Abstraction Abstraction Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it. Generalization Generalization is the process of extracting shared characteristics from two or more classes, and combining them into a generalized superclass. Shared characteristics can be attributes, associations, or methods. Eg : The classes Piece of Luggage and Piece of Cargo partially share the same attributes. From a domain perspective, the two classes are also very similar. During generalization, the shared characteristics are combined and used to create a new superclass Freight . Piece of Luggage and Piece of Cargo become subclasses of the class Freight. Therefore the properties that are common to the classes Piece of Luggage and Piece of Cargo are placed in the superclass Freight - Identification, Weight and ID-Number are those properties. Specialization Specialization means creating new subclasses from an existing class. If it turns out that certain attributes, associations, or methods only apply to some of the objects of the class, a subclass can be created. In the previous example for Generalization, we saw that the classes Piece of Luggage and Piece of Cargo shared similar properties that were placed in a superclass called Freight. When it comes to Specialization, if there is a property that is only applicable to a specific subclass, such as Degree of Hazardousness, that property is placed in the class Piece of Cargo wherein this class also has all the properties of the Freight class with the concept of Generalization. Ways to achieve abstraction? There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%) Abstract Class A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. Some points to remember: An abstract class must be declared with an abstract keyword. It can have abstract and non-abstract methods. It cannot be instantiated. It can have constructors and static methods also. It can have final methods which will force the subclass not to change the body of the method. Abstract Method A method which is declared as abstract and does not have implementation is known as an abstract method. abstract void printStatus(); //no method body and abstract Example of Abstract Class with an Abstract Method abstract class Bike{ // Abstract class abstract void run(); // Abstract method } class Honda4 extends Bike{ void run(){System.out.println("running safely");} public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } } Sample Exercise : To create an abstract class called Bank. To create an abstract method called getRateOfInterest(); To create two subclasses called SBI - 7% and PNB - 5% as two banks that extend the abstract class Bank. To implement different functionalities for the getRateOfInterest() method in the SBI and PNB classes through the concept of method overriding and print out the interest rate inside the main() method created separately in a test class called TestBank Java Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. We will be covering these following topics : Conditional Statements Looping Constructs Usage of this, new, super, static and final keywords String Manipulation Packages Interface Exceptions Data Structures Conditional Statements Decision Making Structures Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Java programming language provides following types of decision making statements. if statement if..else statement nested if statement switch statement IF Statement An if statement consists of a Boolean expression followed by one or more statements. Syntax : if(Boolean_expression) { // Statements will execute if the Boolean expression is true } If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not, the first set of code after the end of the if statement (after the closing curly brace) will be executed. Example public class Test { public static void main(String args[]) { int x = 10; if( x < 20 ) { System.out.print("This is if statement"); } } } IF..ELSE Statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax : if(Boolean_expression) { // Executes when the Boolean expression is true }else { // Executes when the Boolean expression is false } Example public class Test { public static void main(String args[]) { int x = 30; if( x < 20 ) { System.out.print("This is if statement"); }else { System.out.print("This is else statement"); } } } IF..ELSE IF Statement An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if, else if, else statements there are a few points to keep in mind. An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Syntax : if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true }else if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true }else if(Boolean_expression 3) { // Executes when the Boolean expression 3 is true }else { // Executes when the none of the above condition is true. } Example public class Test { public static void main(String args[]) { int x = 30; if( x == 10 ) { System.out.print("Value of X is 10"); }else if( x == 20 ) { System.out.print("Value of X is 20"); }else if( x == 30 ) { System.out.print("Value of X is 30"); }else { System.out.print("This is else statement"); } } } Nested IF Statement It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement. Syntax : if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true } } Example public class Test { public static void main(String args[]) { int x = 30; int y = 10; if( x == 30 ) { if( y == 10 ) { System.out.print("X = 30 and Y = 10"); } } } } SWITCH Statement A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. Syntax : switch(expression) { case value : // Statements break; // optional case value : // Statements break; // optional // You can have any number of case statements. default : // Optional // Statements } Rules for SWITCH Statement The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. Example public class Test { public static void main(String args[]) { // char grade = args[0].charAt(0); char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } } Looping Constructs Loops In Java There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages. Types Of Loops : Java programming language provides the following types of loop to handle looping requirements : While loop For loop Do..While loop While Loop A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true. Syntax : while(Boolean_expression) { // Statements } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non zero value. When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true. When the condition becomes false, program control passes to the line immediately following the loop. Example public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } } For Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax : for(initialization; Boolean_expression; update) { // Statements } This is how it works : The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;). Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop. After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates. Example public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x + 1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } } Do..While Loop A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax : do { // Statements }while(Boolean_expression); Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false. Example public class Test { public static void main(String args[]) { int x = 10; do { System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } } Enhanced For Loop As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays. Syntax : for(declaration : expression) { // Statements } Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array. Example public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names = {"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } } Usage of Keywords Usage of "this" keyword There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. 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. "this" : to refer current class instance variable The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ this.rollno=rollno; // Refers class instance variable rollno this.name=name; // Refers class instance variable name this.fee=fee; // Refers class instance variable fee } void display(){System.out.println(rollno+" "+name+" "+fee);} } class TestThis2{ public static void main(String args[]){ Student s1=new Student(111,"ankit",5000f); Student s2=new Student(112,"sumit",6000f); s1.display(); s2.display(); }} "this" : to invoke current class method You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Example class A{ void m(){System.out.println("hello m");} void n(){ System.out.println("hello n"); //m();//same as this.m() this.m(); // By default added by the compiler } } class TestThis4{ public static void main(String args[]){ A a=new A(); a.n(); }} "this" : to invoke current class constructor The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining. Example class A{ A(){System.out.println("hello a");} A(int x){ this(); // Current class constructor is called. System.out.println(x); } } class TestThis5{ public static void main(String args[]){ A a=new A(10); }} Usage of the "new" keyword When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. Example Let us say that we have a class called Student and we need to instantiate this class. The following syntax does that : Student anil = new Student(); Usage of "super" keyword 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. super can be used to refer immediate parent class instance variable. super can be used to invoke immediate parent class method. super() can be used to invoke immediate parent class constructor. Using "super" to refer parent class instance variable We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. class Animal{ String color="white"; } class Dog extends Animal{ String color="black"; void printColor(){ System.out.println(color); //prints color of Dog class System.out.println(super.color); //prints color of Animal class } } class TestSuper1{ public static void main(String args[]){ Dog d=new Dog(); d.printColor(); }} Using "super" to invoke parent class method The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void eat(){System.out.println("eating bread...");} void bark(){System.out.println("barking...");} void work(){ super.eat(); // Calling the parent class eat() method using super keyword bark(); } } class TestSuper2{ public static void main(String args[]){ Dog d=new Dog(); d.work(); }} Using "super" to invoke parent class constructor The super keyword can also be used to invoke the parent class constructor. class Animal{ Animal(){System.out.println("animal is created");} } class Dog extends Animal{ Dog(){ super(); // using super keyword to access the parent class constructor. System.out.println("dog is created"); } } class TestSuper3{ public static void main(String args[]){ Dog d=new Dog(); }} Note : While using "super" keyword to access the parent class constructor, remember that it has to be in the first line within the subclass constructor. Static Keyword The static keyword in Java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance of the class. The static can be: Variable (also known as a class variable) Method (also known as a class method) Block Nested class Static variable If you declare any variable as static, it is known as a static variable. The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading. Advantages It makes your program memory efficient (i.e., it saves memory). Example //Java Program to demonstrate the use of static variable class Student{ int rollno;//instance variable String name; static String college ="ITS"; //static variable //constructor Student(int r, String n){ rollno = r; name = n; } //method to display the values void display (){System.out.println(rollno+" "+name+" "+college);} } //Test class to show the values of objects public class TestStaticVariable1{ public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //we can change the college of all objects by the single line of code //Student.college="BBDIT"; s1.display(); s2.display(); } } Static Explanation Notice the stack, heap and class area in the diagram. Final Keyword The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. Example Final Variable : class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; // Compile Time Error (Cant change final variable value) } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }//end of class Final Method : class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} Compile Time Error (Cant override final method) public static void main(String args[]){ // Honda honda= new Honda(); honda.run(); } } Final Class : final class Bike{} class Honda1 extends Bike{ // Compile Time Error (Cant extend final class) void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda1 honda= new Honda1(); honda.run(); } } String Manipulation What is a String? Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. Creating Strings The most direct way to create a string is to write : String greeting = "hello world"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters. Example public class StringDemo { public static void main(String args[]) { char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String helloString = new String(helloArray); System.out.println( helloString ); } } Note : The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes. String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. Example public class StringDemo { public static void main(String args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); // Using the length method System.out.println( "String Length is : " + len ); } } Concatenating Strings The String class includes a method for concatenating two strings : string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals "My Name is".concat("Zara"); Strings are most commonly concatenated with the "+" operator "Hello," + " world" + "!" Example public class StringDemo { public static void main(String args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); } } Some String Handling Methods char charAt(int index) - Returns the character at the specified index. int compareTo(Object o) - Compares this String to another Object. String concat(String str) - Concatenates the specified string to the end of this string. boolean equals(Object anObject) - Compares this string to the specified object. boolean equalsIgnoreCase(String anotherString) - Compares this String to another String, ignoring case considerations. Packages Package? A java package is a group of similar types of classes, interfaces and sub-packages. 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. Advantages Of Packages Java package is used to categorize the classes and interfaces so that they can be easily maintained. Java package provides access protection. Java package removes naming collision. Example //save as Simple.java package com.revature; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } } Accessing a package from other packages There are three ways to access the package from outside the package. import package.*; import package.classname; fully qualified name. Using packagename.* If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package. //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save as B.java package mypack; import pack.*; //Importing the package named pack which contains class A. class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } Using packagename.classname If you import package.classname then only declared class of this package will be accessible. //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.A; //Importing class A from packagename pack which gives us access to only A. class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } Using fully qualified name If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class. //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; class B{ public static void main(String args[]){ pack.A obj = new pack.A(); // using fully qualified name obj.msg(); } } Sequence of program Sequence of the program must be package then import then class. Interface Interface? An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. Similarities between an interface and a class An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a .class file. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. Differences between an interface and a class You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class, it is implemented by a class. An interface can extend multiple interfaces. Declaring Interfaces The interface keyword is used to declare an interface. /* File name : NameOfInterface.java */ import java.lang.*; // Any number of import statements public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations\ } An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public. Example /* File name : Animal.java */ interface Animal { public void eat(); public void travel(); } Implementing Interfaces When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. Example /* File name : MammalInt.java */ public class MammalInt implements Animal { public void eat() { System.out.println("Mammal eats"); } public void travel() { System.out.println("Mammal travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } } Rules to Remember : A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class. Extending Interfaces An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. Example // Filename: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } // Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } // Filename: Hockey.java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); } The Hockey interface has four methods, but it inherits two from Sports. Thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports. Extending Multiple Interfaces A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a commaseparated list. Example public interface Hockey extends Sports, Event Exceptions Exceptions? Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.). In Java, an exception is an object that wraps an error event that occurred within a method and contains: Information about the error including its type The state of the program when the error occurred Optionally, other custom information Categories of Exceptions : Checked Exceptions Unchecked Exceptions Errors Checked Exceptions Checked exceptions are those that : The compiler enforces that you handle them explicitly. Methods that generate checked exceptions must declare that they throw them. Methods that invoke other methods that throw checked exceptions must either handle them (they can be reasonably expected to recover) or let them propagate by declaring that they throw them. Example If you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. import java.io.File; import java.io.FileReader; public class FilenotFoundDemo { public static void main(String args[]) { File file = new File("E://file.txt"); //If the file does not exist an exception is thrown. That exception is called as FileNotFoundException FileReader fr = new FileReader(file); } } Unchecked Exceptions Errors and RuntimeExceptions are unchecked — that is, the compiler does not enforce (check) that you handle them explicitly. Methods do not have to declare that they throw them (in the method signatures). It is assumed that the application cannot do anything to recover from these exceptions (at runtime). Example If you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsException occurs. public class Unchecked_Demo { public static void main(String args[]) { int num[] = {1, 2, 3, 4}; System.out.println(num[5]); } } Errors These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Exception Hierarchy All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Catching Exceptions A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following try { // Protected code } catch (ExceptionName e1) { // Catch block } The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Example The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. // File Name : ExcepTest.java import java.io.*; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; // Size 2 System.out.println("Access element three :" + a[3]); // Accessing 3rd element } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } The Throw/Throws Keyword If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. One can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly. Example import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } // Remainder of class definition } Finally Block The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. } Example public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; // Size 2 try { System.out.println("Access element three :" + a[3]); // Accessing 3rd element } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); }finally { // Always executed no matter what! a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } Output : Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Data Structures Array Normally, an array is a collection of similar type of elements that have a contiguous memory location. Java array is an object which contains elements of a similar data type. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. Array in java is index-based, the first element of the array is stored at the 0 index. Advantages Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. Random access: We can get any data located at an index position Disadvantages Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically. Types of Array There are two types of array. Single Dimensional Array Multidimensional Array Example //Java Program to illustrate how to declare, instantiate, initialize //and traverse the Java array. class Testarray{ public static void main(String args[]){ int a[]=new int[5]; //declaration and instantiation a[0]=10; //initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //traversing array for(int i=0;i<a.length;i++) //length is the property of array System.out.println(a[i]); }} Queue The Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. 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 list i.e. it follows the FIFO or the First-In-First-Out principle. LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations. 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. A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following : Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In objectoriented languages, interfaces generally form a hierarchy. Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures. Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections. The List Interface The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements. In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following table. Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another. ArrayList ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. ArrayList inherits AbstractList class and implements List interface. ArrayList is initialized by a size, however the size can increase if collection grows or shrunk if 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. Code to create a generic integer ArrayList : ArrayList<Integer> arrli = new ArrayList<Integer>(); Note : More examples are given below. The Set Interface A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. The Map Interface The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. Several methods throw a NoSuchElementException when no items exist in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map. An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map. Example of List, Set, Map import java.util.*; // All the classes and interfaces are part of the util package public class CollectionsDemo { public static void main(String[] args) { // ArrayList List a1 = new ArrayList(); a1.add("Zara"); a1.add("Mahnaz"); a1.add("Ayan"); System.out.println(" ArrayList Elements"); System.out.print("\t" + a1); // LinkedList List l1 = new LinkedList(); l1.add("Zara"); l1.add("Mahnaz"); l1.add("Ayan"); System.out.println(); System.out.println(" LinkedList Elements"); System.out.print("\t" + l1); // HashSet Set s1 = new HashSet(); s1.add("Zara"); s1.add("Mahnaz"); s1.add("Ayan"); System.out.println(); System.out.println(" Set Elements"); System.out.print("\t" + s1); // HashMap Map m1 = new HashMap(); m1.put("Zara", "8"); m1.put("Mahnaz", "31"); m1.put("Ayan", "12"); m1.put("Daisy", "14"); System.out.println(); System.out.println(" Map Elements"); System.out.print("\t" + m1); } } C# C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft within its .NET initiative led by Anders Hejlsberg. We will learn about this following topics : Program Structure Decision Making Loops Usage of Keywords String Manipulation Namespaces Abstract Class & Virtual Functions Interfaces Exception Handling Collections Program Structure Program Structure? A C# program consists of the following parts : Namespace declaration A class Class methods Class attributes A Main method Statements and Expressions Comments Example using System; namespace HelloWorldApplication { class HelloWorld { static void Main(string[] args) { /* my first program in C# */ Console.WriteLine("Hello World"); Console.ReadKey(); } } } Let us break each line and understand the significance : The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements. The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld. The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the HelloWorld class has only one method Main. The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed. The next line /*...*/ is ignored by the compiler and it is put to add comments in the program. The Main method specifies its behavior with the statement Console.WriteLine("Hello World"); WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen. The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET. Points to Remember C# is case sensitive. All statements and expression must end with a semicolon (;). The program execution starts at the Main method. Unlike Java, program file name could be different from the class name. Decision Making Decision making structures requires the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. C# provides following types of decision making statements : IF Statement IF...ELSE Statement Nested IF Statement SWITCH Statement Nested SWITCH Statement IF Statement An if statement consists of a boolean expression followed by one or more statements. Syntax : if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } If the boolean expression evaluates to true, then the block of code inside the if statement is executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) is executed. Example using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* local variable definition */ int a = 10; /* check the boolean condition using if statement */ if (a < 20) { /* if condition is true then print the following */ Console.WriteLine("a is less than 20"); } Console.WriteLine("value of a is : {0}", a); Console.ReadLine(); } } } IF...ELSE Statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. Syntax : if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ } If the boolean expression evaluates to true, then the if block of code is executed, otherwise else block of code is executed. Example using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* local variable definition */ int a = 100; /* check the boolean condition */ if (a < 20) { /* if condition is true then print the following */ Console.WriteLine("a is less than 20"); } else { /* if condition is false then print the following */ Console.WriteLine("a is not less than 20"); } Console.WriteLine("value of a is : {0}", a); Console.ReadLine(); } } } Nested IF Statement It is always legal in C# to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). Syntax : if( boolean_expression 1) { /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } } You can nest else if...else in the similar way as you have nested if statement. Example using System; namespace DecisionMaking { class Program { static void Main(string[] args) { //* local variable definition */ int a = 100; int b = 200; /* check the boolean condition */ if (a == 100) { /* if condition is true then check the following */ if (b == 200) { /* if condition is true then print the following */ Console.WriteLine("Value of a is 100 and b is 200"); } } Console.WriteLine("Exact value of a is : {0}", a); Console.WriteLine("Exact value of b is : {0}", b); Console.ReadLine(); } } } SWITCH Statement A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. Syntax : switch(expression) { case constant-expression statement(s); break; /* optional */ case constant-expression statement(s); break; /* optional */ : : /* you can have any number of case statements */ default : /* Optional */ statement(s); } Rules : The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. Example using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* local variable definition */ char grade = 'B'; switch (grade) { case 'A': Console.WriteLine("Excellent!"); break; case 'B': case 'C': Console.WriteLine("Well done"); break; case 'D': Console.WriteLine("You passed"); break; case 'F': Console.WriteLine("Better try again"); break; default: Console.WriteLine("Invalid grade"); break; } Console.WriteLine("Your grade is {0}", grade); Console.ReadLine(); } } } Nested SWITCH Statement It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise. Syntax : switch(ch1) { case 'A': Console.WriteLine("This A is part of outer switch" ); switch(ch2) { case 'A': Console.WriteLine("This A is part of inner switch" ); break; case 'B': /* inner B case code */ } break; case 'B': /* outer B case code */ } Example using System; namespace DecisionMaking { class Program { static void Main(string[] args) { int a = 100; int b = 200; switch (a) { case 100: Console.WriteLine("This is part of outer switch "); switch (b) { case 200: Console.WriteLine("This is part of inner switch "); break; } break; } Console.WriteLine("Exact value of a is : {0}", a); Console.WriteLine("Exact value of b is : {0}", b); Console.ReadLine(); } } } Loops Loops? There may be a situation, when you need to execute a block of code several number of times. In general, the statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or a group of statements multiple times and following is the general from of a loop statement in most of the programming languages C# provides following types of loop to handle looping requirements : While Loop For Loop Do...While Loop While Loop A while loop statement in C# repeatedly executes a target statement as long as a given condition is true. Syntax : while(condition) { statement(s); } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. Example using System; namespace Loops { class Program { static void Main(string[] args) { /* local variable definition */ int a = 10; /* while loop execution */ while (a < 20) { Console.WriteLine("value of a: {0}", a); a++; } Console.ReadLine(); } } } For Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax : for ( init; condition; increment ) { statement(s); } The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates. Example using System; namespace Loops { class Program { static void Main(string[] args) { /* for loop execution */ for (int a = 10; a < 20; a = a + 1) { Console.WriteLine("value of a: {0}", a); } Console.ReadLine(); } } } Do...While Loop Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop checks its condition at the end of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax : do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. Example using System; namespace Loops { class Program { static void Main(string[] args) { /* local variable definition */ int a = 10; /* do loop execution */ do { Console.WriteLine("value of a: {0}", a); a = a + 1; } while (a < 20); Console.ReadLine(); } } } Usage of Keywords Usage of "new" keyword Used to create objects and invoke constructors. Class1 obj = new Class1(); It is also used to create instances of anonymous types: var query = from cust in customers select new { Name = cust.Name, Address = cust.PrimaryAddress }; The new operator is also used to invoke the default constructor for value types. int i = new int(); In the preceding statement, i is initialized to 0, which is the default value for the type int Note : If the new operator fails to allocate memory, it throws the exception, OutOfMemoryException. Usage of "sealed" keyword When applied to a class, the sealed modifier prevents other classes from inheriting from it. class A {} sealed class B : A {} In the above example, class B inherits from class A, but no class can inherit from class B. You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties Example class X { protected virtual void F() { Console.WriteLine("X.F"); } protected virtual void F2() { Console.WriteLine("X.F2"); } } class Y : X { sealed protected override void F() { Console.WriteLine("Y.F"); } protected override void F2() { Console.WriteLine("Y.F2"); } } class Z : Y { // Attempting to override F causes compiler error CS0239. // protected override void F() { Console.WriteLine("Z.F"); } // Overriding F2 is allowed. protected override void F2() { Console.WriteLine("Z.F2"); } } In the above example, Z inherits from Y but Z cannot override the virtual function F that is declared in X and sealed in Y. Note : It is an error to use the abstract modifier with a sealed class, because an abstract class must be inherited by a class that provides an implementation of the abstract methods or properties. Usage of "this" keyword The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method. To qualify members hidden by similar names, for example: public class Employee { private string alias; private string name; public Employee(string name, string alias) { // Use this to qualify the members of the class // instead of the constructor parameters. this.name = name; this.alias = alias; } } To pass an object as a parameter to other methods, for example: CalcTax(this); Usage of "static" keyword Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, finalizers, or types other than classes. Example The following class is declared as static and contains only static methods: static class CompanyEmployee { public static void DoSomething() { /*...*/ } public static void DoSomethingElse() { /*...*/ } } A constant or type declaration is implicitly a static member. A static member cannot be referenced through an instance. Instead, it is referenced through the type name. For example, consider the following class: public class MyBaseC { public struct MyStruct { public static int x = 100; } } To refer to the static member x, use the fully qualified name, MyBaseC.MyStruct.x, unless the member is accessible from the same scope: Console.WriteLine(MyBaseC.MyStruct.x); While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field. It is not possible to use this to reference static methods or property accessors. If the static keyword is applied to a class, all the members of the class must be static. Classes and static classes may have static constructors. Static constructors are called at some point between when the program starts and the class is instantiated. String Manipulation Strings? In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class. Creating a String Object By assigning a string literal to a String variable By using a String class constructor By using the string concatenation operator (+) By retrieving a property or calling a method that returns a string By calling a formatting method to convert a value or an object to its string representation Example using System; namespace StringApplication { class Program { static void Main(string[] args) { //from string literal and string concatenation string fname, lname; fname = "Rowan"; lname = "Atkinson"; char []letters= { 'H', 'e', 'l', 'l','o' }; string [] sarray={ "Hello", "From", "Tutorials", "Point" }; string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname); //by using string constructor { 'H', 'e', 'l', 'l','o' }; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); //methods returning string { "Hello", "From", "Tutorials", "Point" }; string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message); //formatting method to convert a value DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat); } } } Properties of the String Class Chars - Gets the Char object at a specified position in the current String object. Length - Gets the number of characters in the current String object. Comparing Strings using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str1 = "This is test"; string str2 = "This is text"; if (String.Compare(str1, str2) == 0) { // Using Compare method Console.WriteLine(str1 + " and " + str2 + " are equal."); } else { Console.WriteLine(str1 + " and " + str2 + " are not equal."); } Console.ReadKey() ; } } } String Contains String using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "This is test"; if (str.Contains("test")) { // Using the Contains method Console.WriteLine("The sequence 'test' was found."); } Console.ReadKey() ; } } } Getting a Substring using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "Last night I dreamt of San Pedro"; Console.WriteLine(str); string substr = str.Substring(23); // Using the Substring method Console.WriteLine(substr); } } } Joining Strings using System; namespace StringApplication { class StringProg { static void Main(string[] string[] starray = new dark", "And the sun shines "I took a trip on a "And when I reached "I made a stop"}; args) { string[]{"Down the way nights are daily on the mountain top", sailing ship", Jamaica", string str = String.Join("\n", starray); // Using the Join method Console.WriteLine(str); } } } Namespaces Namespaces? A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another. Defining a Namespace A namespace definition begins with the keyword namespace followed by the namespace name as follows namespace namespace_name { // code declarations } Example - Without the "using" keyword using System; namespace first_space { class namespace_cl { public void func() { Console.WriteLine("Inside first_space"); } } } namespace second_space { class namespace_cl { public void func() { Console.WriteLine("Inside second_space"); } } } class TestClass { static void Main(string[] args) { first_space.namespace_cl fc = new first_space.namespace_cl(); second_space.namespace_cl sc = new second_space.namespace_cl(); fc.func(); sc.func(); Console.ReadKey(); } } The "using" keyword The using keyword states that the program is using the names in the given namespace. For example, we are using the System namespace in our programs. The class Console is defined there. We just write Console.WriteLine ("Hello there"); We could have written the fully qualified name as System.Console.WriteLine("Hello there"); Example - With the "using" keyword using System; using first_space; // Importing here using second_space; // Importing here namespace first_space { class abc { public void func() { Console.WriteLine("Inside first_space"); } } } namespace second_space { class efg { public void func() { Console.WriteLine("Inside second_space"); } } } class TestClass { static void Main(string[] args) { abc fc = new abc(); // Notice we are not using the fully qualified syntax efg sc = new efg(); // Notice we are not using the fully qualified syntax fc.func(); sc.func(); Console.ReadKey(); } } Abstract Class & Virtual Functions Abstract and Sealed Keywords The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class. The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual. Abstract Classes and Class Members Classes can be declared as abstract by putting the keyword abstract before the class definition. public abstract class A { // Class members here. } An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. public abstract class A { public abstract void DoWork(int i); } Note : Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. public class D { public virtual void DoWork(int i) { // Original implementation. } } public abstract class E : D { public abstract override void DoWork(int i); //Overriding a virtual method } public class F : E { public override void DoWork(int i) { // New implementation. } } Note : If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods. Virtual Functions A virtual method is used to override specified base class implementation when a runtime object is of the derived type. Thus, virtual methods facilitate the consistent functionality of a related object set. For Eg : An example of a virtual method implementation is classes Manager and Clerk, derived from the base class Employee with a CalculateSalary virtual method, which may be overridden in derived classes with the necessary logic for the appropriate type. A list of Employee type objects may be called at runtime to calculate a salary - without knowing the specific implementation type. Difference between Virtual Function and Abstract Method An abstract function cannot have functionality. Any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class. A virtual function has the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override it, and provide your own functionality. Interfaces Interface? An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow. Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities. Declaring Interfaces Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default . public interface ITransactions { // interface members void showTransaction(); double getAmount(); } Example In the below example, we are using an interface called ITransactions with two methods showTransaction() and getAmount(). We then create a class called Transaction with which we implement the functionalities for both the methods in the interface ITransactions. using System.Collections.Generic; using System.Linq; using System.Text; using System; namespace InterfaceApplication { public interface ITransactions { // interface members void showTransaction(); double getAmount(); } public class Transaction : ITransactions { private string tCode; private string date; private double amount; public Transaction() { tCode = " "; date = " "; amount = 0.0; } public Transaction(string c, string d, double a) { tCode = c; date = d; amount = a; } public double getAmount() { return amount; } public void showTransaction() { Console.WriteLine("Transaction: {0}", tCode); Console.WriteLine("Date: {0}", date); Console.WriteLine("Amount: {0}", getAmount()); } } class Tester { static void Main(string[] args) { Transaction t1 = new Transaction("001", "8/10/2012", 78900.00); Transaction t2 = new Transaction("002", "9/10/2012", 451900.00); t1.showTransaction(); t2.showTransaction(); Console.ReadKey(); } } } Exception Handling Exception? An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw. try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. Syntax : Assuming a block raises an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: try { // statements causing exception } catch( ExceptionName e1 ) { // error handling code } catch( ExceptionName e2 ) { // error handling code } catch( ExceptionName eN ) { // error handling code } finally { // statements to be executed } Exception Classes C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes. The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception. Handling Exceptions C# provides a structured solution to the exception handling in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements. These error handling blocks are implemented using the try, catch, and finally keywords. using System; namespace ErrorHandlingApplication { class DivNumbers { int result; DivNumbers() { result = 0; } public void division(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.division(25, 0); Console.ReadKey(); } } } Throwing Objects You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as Catch(Exception e) { ... Throw e } Collections Arrays in C#? An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array in C#, you can use the following syntax : datatype[] arrayName; where, datatype is used to specify the type of elements in the array. [ ] specifies the rank of the array. The rank specifies the size of the array. arrayName specifies the name of the array. Initializing Arrays Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. Array is a reference type, so you need to use the new keyword to create an instance of the array. double[] balance = new double[10]; Assigning Values to an Array You can assign values to individual array elements, by using the index number, like double[] balance = new double[10]; balance[0] = 4500.0; You can assign values to the array at the time of declaration, as shown double[] balance = { 2340.0, 4523.69, 3421.0}; You can also create and initialize an array, as shown int [] marks = new int[5] { 99, 98, 92, 97, 95}; You may also omit the size of the array, as shown int [] marks = new int[] { 99, 98, 92, 97, 95}; Accessing Array Elements using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n */ for ( i = 0; i < 10; i++ ) { //Setting the array with values from 100 to 109 n[ i ] = i + 100; } /* output each array element's value */ for (j = 0; j < 10; j++ ) { //Traversing through the array to display the values Console.WriteLine("Element[{0}] = {1}", j, n[j]); } Console.ReadKey(); } } } Collections in C#? Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces. Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#. The following are the various commonly used classes of the System.Collection namespace : ArrayList HashTable Stack Queue ArrayList It represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, adding, searching and sorting items in the list. Example using System; using System.Collections; namespace CollectionApplication { class Program { static void Main(string[] args) { ArrayList al = new ArrayList(); //Instantiating an ArrayList Console.WriteLine("Adding some numbers:"); al.Add(45); //Adding elements into the ArrayList al.Add(78); al.Add(33); al.Add(56); al.Add(12); al.Add(23); al.Add(9); Console.WriteLine("Capacity: {0} ", al.Capacity); Console.WriteLine("Count: {0}", al.Count); Console.Write("Content: "); foreach (int i in al) { //Traversing through an ArrayList Console.Write(i + " "); } Console.WriteLine(); Console.Write("Sorted Content: "); al.Sort(); //Sorting an ArrayList foreach (int i in al) { //Traversing through an ArrayList Console.Write(i + " "); } Console.WriteLine(); Console.ReadKey(); } } } HashTable The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection. A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection. Example using System; using System.Collections; namespace CollectionsApplication { class Program { static void Main(string[] args) { Hashtable ht = new Hashtable(); //Instantiating a HashTable ht.Add("001", HashTable ht.Add("002", ht.Add("003", ht.Add("004", ht.Add("005", ht.Add("006", ht.Add("007", "Zara Ali"); //Adding elements into the "Abida Rehman"); "Joe Holzner"); "Mausam Benazir Nur"); "M. Amlan"); "M. Arif"); "Ritesh Saikia"); if (ht.ContainsValue("Nuha Ali")) { //Checks if a value is in the HashTable Console.WriteLine("This student name is already in the list"); } else { ht.Add("008", "Nuha Ali"); //If not adds the value to the HashTable } // Get a collection of the keys. ICollection key = ht.Keys; //Get the keys alone foreach (string k in key) { //Traverse and display the keys & value Console.WriteLine(k + ": " + ht[k]); } Console.ReadKey(); } } } Stack It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Example using System; using System.Collections; namespace CollectionsApplication { class Program { static void Main(string[] args) { Stack st = new Stack(); //Instantiating a Stack st.Push('A'); //Pushing items to the top of the stack st.Push('M'); st.Push('G'); st.Push('W'); Console.WriteLine("Current stack: "); foreach (char c in st) { //Traversing through the stack Console.Write(c + " "); } Console.WriteLine(); st.Push('V'); //Adding more items to the stack {V,W,G,M,A} current state st.Push('H'); //Adding more items to the stack {H,V,W,G,M,A} - current state Console.WriteLine("The next poppable value in stack: {0}", st.Peek()); Console.WriteLine("Current stack: "); foreach (char c in st) { //Traversing through the stack Console.Write(c + " "); } Console.WriteLine(); Console.WriteLine("Removing values "); st.Pop(); //Popping elements from the top of the stack {H} st.Pop(); //Popping elements from the top of the stack {V} st.Pop(); //Popping elements from the top of the stack {W} Console.WriteLine("Current stack: "); foreach (char c in st) { //Traversing through the stack {G,M,A} Console.Write(c + " "); } } } } Queue It represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Example using System; using System.Collections; namespace CollectionsApplication { class Program { static void Main(string[] args) { Queue q = new Queue(); //Instantiating a Queue q.Enqueue('A'); q.Enqueue('M'); q.Enqueue('G'); q.Enqueue('W'); current state //Adding //Adding //Adding //Adding elements elements elements elements into into into into a a a a Queue Queue Queue Queue {A,M,G,W} - Console.WriteLine("Current queue: "); foreach (char c in q) Console.Write(c + " "); //Traversal using foreach loop Console.WriteLine(); q.Enqueue('V'); //Adding elements into a Queue q.Enqueue('H'); //Adding elements into a Queue {A,M,G,W,V,H} - current state Console.WriteLine("Current queue: "); foreach (char c in q) Console.Write(c + " "); //Traversal using foreach loop Console.WriteLine(); Console.WriteLine("Removing some values "); char ch = (char)q.Dequeue(); //Removing elements from queue {A} Console.WriteLine("The removed value: {0}", ch); ch = (char)q.Dequeue(); //Removing elements from queue {M} Console.WriteLine("The removed value: {0}", ch); Console.ReadKey(); } } } Database/SQL Database A database is a collection of information that is organized so that it can be easily accessed, managed and updated. Relational Database A relational database is a type of database. It uses a structure that allows us to identify and access data in relation to another piece of data in the database. Often, data in a relational database is organized into tables. Tables : Rows and Columns Tables can have hundreds, thousands, sometimes even millions of rows of data. These rows are often called records. Tables can also have many columns of data. Columns are labeled with a descriptive name (say, age for example) and have a specific data type. Relational Database Management System A relational database management system (RDBMS) is a program that allows you to create, update, and administer a relational database. Most relational database management systems use the SQL language to access the database. SQL - Structured Query Language SQL (Structured Query Language) is a programming language used to communicate with data stored in a relational database management system. SQL syntax is similar to the English language, which makes it relatively easy to write, read, and interpret. Many RDBMSs use SQL (and variations of SQL) to access the data in tables. For example, SQLite is a relational database management system. SQLite contains a minimal set of SQL commands (which are the same across all RDBMSs). Other RDBMSs may use other variants. Why do we need SQL? Allows users to access data in the relational database management systems. Allows users to describe the data. Allows users to define the data in a database and manipulate that data. Allows to embed within other languages using SQL modules, libraries & pre-compilers. Allows users to create and drop databases and tables. Allows users to create view, stored procedure, functions in a database. Allows users to set permissions on tables, procedures and views. SQL Architecture Following is a simple diagram showing the SQL Architecture Primary Key A primary key is a field in a table which uniquely identifies each row/record in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key. If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s). Create Primary Key Generally, the primary key is created while creating the database and the table. The primary key can also be created after the creation of the table as shown below. CREATE TABLE CUSTOMERS( ID INT NOT NULL, // To set a primary key on this column ID NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) ); ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID); Foreign Key A foreign key is a key used to link two tables together. This is sometimes also called as a referencing key. A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table. The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table. Example Consider the following two tables, "Customers" and "Orders" CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) ); CREATE TABLE ORDERS ( ID INT NOT NULL, DATE DATETIME, CUSTOMER_ID INT references CUSTOMERS(ID), AMOUNT double, PRIMARY KEY (ID) ); Once the tables have been created, the foreign key can be created using the following syntax : ALTER TABLE ORDERS ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID); SQL Statements DDL - Data Definition Language - CREATE, ALTER, DROP DML - Data Manipulation Language - SELECT, INSERT, UPDATE, DELETE DCL - Data Control Language - GRANT, REVOKE TCL - Transaction Control Language - SAVEPOINT, ROLLBACK, COMMIT SELECT Query The SQL SELECT statement is used to fetch the data from a database table which returns this data in the form of a result table. These result tables are called result-sets. SELECT column1, column2, columnN FROM table_name; If you want to fetch all the fields available in the field, then you can use the following syntax. SELECT * FROM table_name; Example Consider the following "Customers" table. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ SELECT ID, NAME, SALARY FROM CUSTOMERS; // Selecting columns SQL Where The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement. Syntax : SELECT column1, column2, columnN FROM table_name WHERE [condition] Example Using the same "Customers" table as before and one would like to retrieve all the names of customers who's age is greater than 20, the following query can be used. SELECT CUSTOMERS.AGE from CUSTOMERS where AGE > 20; // Can use DB name as prefix before column name. INSERT Query The SQL INSERT INTO Statement is used to add new rows of data to a table in the database. Syntax : There are two basic syntax's of the INSERT INTO statement which are shown below. INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN); Example INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'kaushik', 23, 'Kota', 2000.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 ); INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Komal', 22, 'MP', 4500.00 ); SQL Joins The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each. Example Consider the following tables : Customers and Orders CUSTOMERS Table +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ ORDERS Table +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Let us join these two tables with a SELECT Query : SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS INNER JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; Different Types Of Joins INNER JOIN LEFT JOIN RIGHT JOIN FULL JOIN Web Development In the realm of web development, we will look at the three most important foundation for a frontend based application. They are : HTML CSS JavaScript HTML HTML? HTML is the standard markup language for creating Web pages. HTML stands for Hyper Text Markup Language HTML describes the structure of Web pages using markup HTML elements are the building blocks of HTML pages HTML elements are represented by tags HTML tags label pieces of content such as "heading", "paragraph", "table", and so on Browsers do not display the HTML tags, but use them to render the content of the page Simple HTML Document <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> Explanation The <!DOCTYPE html> declaration defines this document to be HTML5 The <html> element is the root element of an HTML page The <head> element contains meta information about the document The <title> element specifies a title for the document The <body> element contains the visible page content The <h1> element defines a large heading The <p> element defines a paragraph HTML Links - Hyperlinks HTML links are hyperlinks. You can click on a link and jump to another document. When you move the mouse over a link, the mouse arrow will turn into a little hand. Syntax : <a href="url">link text</a> Example <a href="https://app.revature.com">Visit our learning platform</a> HTML Images In HTML, images are defined with the <img> tag. The <img> tag is empty, it contains attributes only, and does not have a closing tag. The src attribute specifies the URL (web address) of the image: Example <img src="img_chania.jpg" alt="Flowers in Chania"> HTML Lists There are two types of lists in HTML : Ordered List Unordered List Unordered Lists An unordered list starts with the <ul> tag. Each list item starts with the <li> tag. <ul> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> Ordered Lists An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. <ol> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol> CSS CSS? CSS stands for Cascading Style Sheets CSS describes how HTML elements are to be displayed on screen, paper, or in other media CSS saves a lot of work. It can control the layout of multiple web pages all at once External stylesheets are stored in CSS files Example body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; } Styling HTML with CSS CSS can be added to HTML elements in 3 ways: Inline - by using the style attribute in HTML elements Internal - by using a <style> element in the <head> section External - by using an external CSS file Inline CSS An inline CSS is used to apply a unique style to a single HTML element. An inline CSS uses the style attribute of an HTML element. The following example sets the text color of the <h1> element to blue: <h1 style="color:blue;">This is a Blue Heading</h1> Internal CSS An internal CSS is used to define a style for a single HTML page. An internal CSS is defined in the <head> section of an HTML page, within a <style> element: <!DOCTYPE html> <html> <head> <style> body {background-color: powderblue;} h1 {color: blue;} p {color: red;} </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html> External CSS An external style sheet is used to define the style for many HTML pages. With an external style sheet, you can change the look of an entire web site, by changing one file! To use an external style sheet, add a link to it in the <head> section of the HTML page: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html> //styles.css file body { background-color: powderblue; } h1 { color: blue; } p { color: red; } CSS Selectors In CSS, selectors are patterns used to select the element(s) you want to style. Some of the CSS selectors are described in the image. JavaScript JavaScript? JavaScript is the Programming Language for the Web JavaScript can update and change both HTML and CSS JavaScript can calculate, manipulate and validate data Syntax : var x, y; x = 5; y = 6; z = x + y; // How to declare variables // How to assign values // How to compute values Strings are text, written within double or single quotes: "John Doe" 'John Doe' JavaScript Variables In a programming language, variables are used to store data values. JavaScript uses the var keyword to declare variables. An equal sign is used to assign values to variables var x; x = 6; // x is assigned the value of 6 Comparison Operators The ‘==’ operator tests for abstract equality i.e. it does the necessary type conversions before doing the equality comparison. But the ‘===’ operator tests for strict equality i.e it will not do the type conversion hence if the two values are not of the same type, when compared, it will return false. Example <script> // In R.H.S. string "3" is converted into // number 3, hence returns true. document.write(9 == "9"); // used for next line document.write('<br>') // Here no type conversion takes place, // hence returns false document.write(9 === "9"); </script> Output: true false Exercise Write a simple JavaScript program that on button click displays the current timestamp on screen. <!DOCTYPE html> <html> <body> <h2>My First JavaScript</h2> <button type="button" onclick="document.getElementById('demo').innerHTML = Date()"> // using the Date() function Click me to display Date and Time.</button> <p id="demo"></p> // Using the id attribute </body> </html> SDLC SDLC? SDLC (Software Development Life Cycle) is the process of developing software through business needs, analysis, design, implementation and maintenance The Phases of SDLC Investigation System Analysis Design Testing Operations and Maintenance Investigation The 1st stage of SDLC is the investigation phase. During this stage, business opportunities and problems are identified, and information technology solutions are discussed. Multiple alternative projects may be suggested and their feasibility analyzed. Operational feasibility is assessed, and it is determined whether or not the project fits with the current business environment, and to what degree it addresses business objects. In addition, an economic feasibility investigation is conducted to judge the costs and benefits of the project. Technical feasibility must also be analyzed to determine if the available hardware and software resources are sufficient to meet expected specifications The results of the feasibility study can then be compiled into a report, along with preliminary specifications. When the investigation stage ends, a decision whether or not to move forward with the project should be made. System Analysis The goal of system analysis is to determine where the problem is in an attempt to fix the system.This step involves breaking down the system in different pieces to analyze the situation, analyzing project goals, breaking down what needs to be created and attempting to engage users so that definite requirements can be defined. Design In systems design the design functions and operations are described in detail, including screen layouts, business rules, process diagrams and other documentation. The output of this stage will describe the new system as a collection of modules or subsystems. The design stage takes as its initial input the requirements identified in the approved requirements document. For each requirement, a set of one or more design elements will be produced as a result of interviews, workshops, and/or prototype efforts. Design elements describe the desired software features in detail, and generally include functional hierarchy diagrams, screen layout diagrams, tables of business rules, business process diagrams, pseudo-code, and a complete entity-relationship diagram with a full data dictionary. These design elements are intended to describe the software in sufficient detail that skilled programmers may develop the software with minimal additional input design. Testing The code is tested at various levels in software testing. Unit, system and user acceptance testings are often performed. Some testing methods : Defect testing the failed scenarios, including defect tracking Path testing Data set testing Unit testing System testing Integration testing Black-box testing White-box testing Regression testing Automation testing User acceptance testing Software performance testing Operations and Maintenance The deployment of the system includes changes and enhancements before the decommissioning or sunset of the system. Maintaining the system is an important aspect of SDLC. As key personnel change positions in the organization, new changes will be implemented, which will require system.