🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Introduction to Programming Language Basics (Concepts, Vocabulary & Operators) Department of Information Technology 1 What is a Programming Language A programming language is a set of instructions and syntax used to create software...

Introduction to Programming Language Basics (Concepts, Vocabulary & Operators) Department of Information Technology 1 What is a Programming Language A programming language is a set of instructions and syntax used to create software programs. It is a formal language that specifies a set of instructions for a computer to perform specific tasks. It’s used to write software programs and applications, and to control and manipulate computer systems. There are many different programming languages, each with its own syntax, structure, and set of commands. Department of Information Technology 2 Some of the key features of programming languages includes: 1. Syntax: The specific rules and structure used to write code in a programming language. 2. Data Types: The type of values that can be stored in a program, such as numbers, strings, and booleans. 3. Variables: Named memory locations that can store values. Department of Information Technology 3 4. Operators: Symbols used to perform operations on values, such as addition, subtraction, and comparison. 5. Control Structures: Statements used to control the flow of a program, such as if-else statements, loops, and function calls. 6. Libraries and Frameworks: Collections of pre-written code that can be used to perform common tasks and speed up development. 7. Paradigms: The programming style or philosophy used in the language, such as procedural, object-oriented, or functional. Department of Information Technology 4 What is a computer? A computer is a device that can accept human instruction, processes it, and responds to it or a computer is a computational device that is used to process the data under the control of a computer program. Program is a sequence of instruction along with data. Department of Information Technology 5 The basic components of a computer are: 1. Input unit 2. Central Processing Unit(CPU) 3. Output unit Department of Information Technology 6 The CPU is further divided into three parts: 1. Memory unit 2. Control unit 3. Arithmetic Logic unit CPU - is mostly known as the brain of computer because it accepts data, provides temporary memory space to it until it is stored(saved) on the hard disk, performs logical operations on it and hence processes(here also means converts) data into information. Department of Information Technology 7 Software is a set of programs that performs multiple tasks together. An operating system is also software (system software) that helps humans to interact with the computer system. Program Processing raw data Desired Output Department of Information Technology 8 Most Popular Programming Languages C Python C++ Java SCALA C# R Ruby Swift JavaScript Department of Information Technology 9 What is Java? Developed by Sun Microsystems in 1995, Java is a highly popular, object-oriented programming language and later acquired by Oracle Corporation. This platform independent programming language is utilized for Android development, web development, artificial intelligence, cloud applications, and much more. Department of Information Technology 10 Implementation of a Java application program: 1. Creating the program 2. Compiling the program 3. Running the program Department of Information Technology 11 Creating Program class Test { public static void main(String []args) { System.out.println(“My First Java Program.”); } }; File -> Save -> d:\Test.java Department of Information Technology 12 Compiling the program To compile the program, we must run the Java compiler (javac), with the name of the source file on “command prompt” like as follows If everything is OK, the “javac” compiler creates a file called “Test.class” containing byte code of the program. Department of Information Technology 13 Running the program We need to use the Java Interpreter to run a program. Department of Information Technology 14 Basics of Java Java program is an object-oriented programming language, that means java is the collection of objects, and these objects communicate through method calls to each other to work together. Department of Information Technology 15 Basic Terminologies in Java 1. Class - The class is a blueprint (plan) of the instance of a class (object). It can be defined as a logical template that share common properties and methods. Example1: Blueprint of the house is class. Example2: In real world, Alice is an object of the “Human” class. Department of Information Technology 16 2. Objects - The object is an instance of a class. It is an entity that has behavior and state. Example: Dog, Cat, Monkey etc. are the object of “Animal” class. Behavior: Running on the road. Department of Information Technology 17 3. Method - The behavior of an object is the method. Example: The fuel indicator indicates the amount of fuel left in the car. 4. Instance variables: Every object has its own unique set of instance variables. The state of an object is generally created by the values that are assigned to these instance variables. Example: Steps to compile and run a java program in a console Department of Information Technology 18 5. public - It is an access specifier. Public means this function is visible to all. 6. static - static is again a keyword used to make a function static. To execute a static function you do not have to create an Object of the class. 7. void - It is the return type, meaning this function will not return anything. 8. main - main() method is the most important method in a Java program. This is the method which is executed, hence all the logic must be inside the main() method. If a java class is not having a main() method, it causes compilation error. Department of Information Technology 19 9. String[] args - This is used to signify that the user may opt to enter parameters to the Java Program at command line. We can use both String[] args or String args[]. Java compiler would accept both forms. 10. System.out.println - This is used to print anything on the console like “printf” in C language. Department of Information Technology 20 Classes and Objects In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class. Department of Information Technology 21 Java Classes A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class while a particular student named Ravi is an object. Department of Information Technology 22 Properties of Java Classes 1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created. 2. Class does not occupy memory. 3. Class is a group of variables of different data types and a group of methods. 4. A Class in Java can contain: a. Data member b. Method c. Constructor d. Nested Class e. Interface Department of Information Technology 23 Class declaration in Java // Java Program for class example class Student { // data member (also instance variable) int id; // data member (also instance variable) String name; public static void main(String args[]) { // creating an object of // Student Student s1 = new Student(); System.out.println(s1.id); System.out.println(s1.name); } } Department of Information Technology 24 Components of Java Classes 1. Modifiers: A class can be public or has default access 2. Class keyword: class keyword is used to create a class. 3. Class name: The name should begin with an initial letter (capitalized by convention). 4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 6. Body: The class body is surrounded by braces, { }. Department of Information Technology 25 Components of Java Classes Note: Constructors are used for initializing new objects. Fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects. Access Modifiers in Java: private (accessible within the class where defined) default or package-private (when no access modifier is specified) protected (accessible only to classes that subclass your class directly within the current or different package) public (accessible from any class) Department of Information Technology 26 Java Objects An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities. Objects are the instances of a class that are created to use the attributes and methods of a class. A typical Java program creates many objects, which as you know, interact by invoking methods. Department of Information Technology 27 Java object consists of: 1. State: It is represented by attributes of an object. It also reflects the properties of an object. 2. Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects. 3. Identity: It gives a unique name to an object and enables one object to interact with other objects. Department of Information Technology 28 Example of an object: dog Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, and “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”. Department of Information Technology 29 Declaring an object When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. Department of Information Technology 30 Example: Class Dog Department of Information Technology 31 Initializing a Java object Department of Information Technology 32 Difference between Java Class and Objects Department of Information Technology 33 Java Variables In Java, Variables are the data containers that save the data values during Java program execution. Every Variable in Java is assigned a data type that designates the type and quantity of value it can hold. A variable is a memory location name for the data. Java variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Variables in Java are only a name given to a memory location. All the operations done on the variable affect that memory location. In Java, all variables must be declared before use. Department of Information Technology 34 How to Declare Variables in Java? Department of Information Technology 35 How to Initialize Variables in Java? It can be perceived with the help of 3 components that are as follows: datatype: Type of data that can be stored in this variable. variable_name: Name given to the variable. value: It is the initial value stored in the variable. Department of Information Technology 36 Types of Variables in Java 1. Local Variables 2. Instance Variables 3. Static Variables Department of Information Technology 37 Local Variables A variable defined within a block or method or constructor is called a local variable. The Local variable is created at the time of declaration and destroyed after exiting from the block or when the call returns from the function. The scope of these variables exists only within the block in which the variables are declared, i.e., we can access these variables only within that block. Initialization of the local variable is mandatory before using it in the defined scope. // Java Program to implement // Local Variables import java.io.*; class Test{ public static void main(String[] args) { // Declared a Local Variable int var = 10; // This variable is local to this main method only System.out.println("Local Variable: " + var); } } Department of Information Technology 38 Instance Variables Instance variables are non-static variables and are declared in a class outside of any method, constructor, or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier, then the default access specifier will be used. Initialization of an instance variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc. Instance variables can be accessed only by creating objects. We initialize instance variables using constructors while creating an object. We can also use instance blocks to initialize the instance variables. Department of Information Technology 39 Instance Variables Department of Information Technology 40 Static Variables Static variables are also known as class variables. declared similarly to instance variables. The difference is that static variables are declared using the static keyword within a class outside of any method, constructor, or block. we can only have one copy of a static variable per class created at the start of program execution and destroyed automatically when execution ends. Initialization of a static variable is not mandatory. Its default value is dependent on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc. Static variables cannot be declared locally inside an instance method. Department of Information Technology 41 Static Variables Department of Information Technology 42 Differences Between the Instance and the Static Variables Each object will have its own copy of an instance variable, class Test whereas we can only have one copy of a static variable per class, { irrespective of how many objects we create. Thus, static variables // Static variable are good for memory management. static int a; Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of the // Instance variable int b; instance variable. In the case of a static variable, changes will be } reflected in other objects as static variables are common to all objects of a class. We can access instance variables through object references, and static variables can be accessed directly using the class name. Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed. Static variables are created when the program starts and destroyed when the program stops. Department of Information Technology 43 Syntax 1. Comments in Java a. Single line Comment b. Multi-line Comment c. Documentation Comment. Also called a doc comment. 2. Source File Name : The name of a source file should exactly match the public class name with the extension of.java. The name of the file can be a different name if it does not have any public class. Assume you have a public class Test. Test.java // valid syntax test.java // invalid syntax 3. Case Sensitivity : Java is a case-sensitive language, which means that the identifiers AB, Ab, aB, and ab are different in Java. System.out.println("ThisisaTest"); // valid syntax system.out.println("ThisisaTest"); // invalid syntax because of the first letter of System keyword is always uppercase. Department of Information Technology 44 Syntax 4. Class Names a. The first letter of the class should be in Uppercase (lowercase is allowed but discouraged). b. If several words are used to form the name of the class, each inner word’s first letter should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are numbers and currency symbols, although the latter are also discouraged because they are used for a special purpose (for inner and anonymous classes). class MyJavaProgram // valid syntax class 1Program // invalid syntax class My1Program // valid syntax class $Program // valid syntax, but discouraged class My$Program // valid syntax, but discouraged (inner class Program inside the class My) class myJavaProgram // valid syntax, but discouraged Department of Information Technology 45 Syntax 5. public static void main(String [] args) - The method main() is the main entry point into a Java program; this is where the processing starts. Also allowed is the signature public static void main(String… args). 6. Method Names a. All the method names should start with a lowercase letter (uppercase is also allowed but lowercase is recommended). b. If several words are used to form the name of the method, then each first letter of the inner word should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are digits and currency symbols. public void employeeRecords() // valid syntax public void EmployeeRecords() // valid syntax, but discouraged Department of Information Technology 46 Syntax 7. Identifiers in java - Identifiers are the names of local variables, instance and class variables, and labels, but also the names for classes, packages, modules and methods. All Unicode characters are valid, not just the ASCII subset. a. All identifiers can begin with a letter, a currency symbol or an underscore (_). According to the convention, a letter should be lower case for variables. b. The first character of identifiers can be followed by any combination of letters, digits, currency symbols and the underscore. The underscore is not recommended for the names of variables. Constants (static final attributes and enums) should be in all Uppercase letters. c. Most importantly identifiers are case-sensitive. d. A keyword cannot be used as an identifier since it is a reserved word and has some special meaning. Legal identifiers: MinNumber, total, ak74, hello_world, $amount, _under_value Illegal identifiers: 74ak, -amount Department of Information Technology 47 Syntax 8. White spaces in Java - A line containing only white spaces, possibly with the comment, is known as a blank line, and the Java compiler totally ignores it. 9. Access Modifiers: These modifiers control the scope of class and methods. Access Modifiers: default, public, protected, private. Non-access Modifiers: final, abstract, static, transient, synchronized, volatile, native. 10. Understanding Access Modifiers: Department of Information Technology 48 Syntax 11. Java Keywords - Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Department of Information Technology 49 Java Identifiers In Java, identifiers are used for identification purposes. Java Identifiers can be a class name, method name, variable name, or label. Example: public class Test { public static void main(String[] args) { int a = 20; } } In the above Java code, we have 5 identifiers namely: Test: class name main: method name String: predefined class name args: variable name a: variable name Department of Information Technology 50 Rules For Defining Java Identifiers The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “test@” is not a valid Java identifier as it contains a ‘@’ a special character. Identifiers should not start with digits([0-9]). For example “123test” is not a valid Java identifier. Java identifiers are case-sensitive. There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15 letters only. Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement as a while is a reserved word. There are 53 reserved words in Java. Department of Information Technology 51 Java Data Types Java is statically typed and also a strongly typed language because, in Java, each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the Java data types. Java has two categories in which data types are segregated: 1. Primitive Data Type: such as Boolean, char, int, short, byte, long, float, and double 2. Non-Primitive Data Type or Object Data type: such as String, Array, etc. Department of Information Technology 52 Java Data Types Department of Information Technology 53 Boolean Data Type The Boolean data type represents a logical value that can be either true or false. Default value is false. Example: boolean booleanVar; Department of Information Technology 54 Integer Data Type The integer data type basically represents whole numbers (no fractional parts) and its default value is 0. Example: int intVar; Department of Information Technology 55 Float Data Type The float data types are used to store positive and negative numbers with a decimal point, like 35.3, -2.34, or 3597.34987. The float data type has two keywords: Type. Size. Range. It’s default value is 0.0. Department of Information Technology 56 Char Data Type The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c' For example, if you define a CHAR column as CHAR(10), the column has a fixed length of 10 bytes, not 10 characters. Department of Information Technology 57 Java Data Types Department of Information Technology 58 Strings Strings are defined as an array of characters. The difference between a character array and a string in Java is, that the string is designed to hold a sequence of characters in a single variable whereas, a character array is a collection of separate char-type entities. Syntax: Declaring a string = “”; Example: // Declare String without using new operator String s = "TestString"; Department of Information Technology 59 Array An Array is a group of like-typed variables that are referred to by a common name. The following are some important points about Java arrays. A Java array variable can also be declared like other variables with [] after the data type. The variables in the array are ordered and each has an index beginning with 0. Java array can also be used as a static field, a local variable, or a method parameter. The size of an array must be specified by an int value and not long or short. An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class, depending on the definition of the array. Department of Information Technology 60 Declaring an Array: Syntax for instantiating an Array: var-name = new type [size]; Examples: int[] arr; arr = new int; arr = 10; arr = 20; Department of Information Technology 61 Operators in Java Operators in Java are the symbols used for performing specific operations in Java. Operators make tasks like addition, multiplication, etc which look easy although the implementation of these tasks is quite complex. Department of Information Technology 62 Types of Operators in Java 1. Arithmetic Operators 2. Unary Operators 3. Assignment Operator 4. Relational Operators 5. Logical Operators 6. Ternary Operator 7. Bitwise Operators 8. Shift Operators 9. instance of operator Department of Information Technology 63 Arithmetic Operators They are used to perform simple arithmetic operations on primitive data types. + : Addition class ArithmeticOps { // Main Function – : Subtraction public static void main (String[] args) { * : Multiplication // Arithmetic operators / : Division int a = 10; % : Modulo int b = 3; System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); } } Department of Information Technology 64 Arithmetic Operators They are used to perform simple arithmetic operations on primitive data types. + : Addition – : Subtraction * : Multiplication / : Division % : Modulo Department of Information Technology 65 Unary Operators Unary operators need only one operand. They are used to increment, decrement, or negate a value. – : Unary minus, used for negating the values. + : Unary plus indicates the positive value (numbers are positive without this, however). It performs an automatic conversion to int when the type of its operand is the byte, char, or short. This is called unary numeric promotion. ++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment operators. ○ Post-Increment: Value is first used for computing the result and then incremented. ○ Pre-Increment: Value is incremented first, and then the result is computed. – – : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operators. ○ Post-decrement: Value is first used for computing the result and then decremented. ○ Pre-Decrement: The value is decremented first, and then the result is computed. ! : Logical not operator, used for inverting a boolean value. Department of Information Technology 66 Unary Operators class UnaryOps{ // main function public static void main(String[] args) { // Integer declared int a = 10; int b = 10; // Using unary operators System.out.println("Postincrement : " + (a++)); System.out.println("Preincrement : " + (++a)); System.out.println("Postdecrement : " + (b--)); System.out.println("Predecrement : " + (--b)); } } Department of Information Technology 67 Assignment Operator ‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associativity, i.e. value given on the right-hand side of the operator is assigned to the variable on the left, and therefore right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is: variable = value; In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement. For example, instead of a = a+5, we can write a += 5. Department of Information Technology 68 Relational Operators These operators are used to check for relations like equality, greater than, and less than. They return boolean results after the comparison and are extensively used in looping statements as well as conditional if-else statements. The general format is: variable relation_operator value Some of the relational operators are: ==, Equal to returns true if the left-hand side is equal to the right-hand side. !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side. =, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-hand side. Department of Information Technology 69 Relational Operators class RelOps{ // main function public static void main(String[] args) { // Comparison operators int a = 7; int b = 2; int c = 4; System.out.println("a > b: " + (a > b)); System.out.println("a != c: " + (a != c)); } } Department of Information Technology 70 Logical Operators These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Java also has “Logical NOT”, which returns true when the condition is false and vice-versa Conditional operators are: &&, Logical AND: returns true when both conditions are true. ||, Logical OR: returns true if at least one condition is true. !, Logical NOT: returns true when a condition is false and vice-versa Department of Information Technology 71 Logical Operators class LogOps{ // Main Function public static void main (String[] args) { // Logical operators boolean m = false; boolean n = true; System.out.println("m && n: " + (m && n)); } Department of Information Technology 72 Ternary Operator The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name Ternary. The general format is: condition ? if true : if false The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute the statements after the ‘:’ public class operators { public static void main(String[] args) { int a = 2, b = 1, result; result = ((a < b) ? b : a ); System.out.println("Max number is = " + result); } } Department of Information Technology 73 How to Take Input From User in Java? Java brings various Streams with its I/O package that helps the user perform all the Java input-output operations. These streams support all types of objects, data types, characters, files, etc. to fully execute the I/O operations. There are two ways by which we can take Java input from the user or from a file: BufferedReader Class Scanner Class Department of Information Technology 74 Using BufferedReader Class for String Input It is a simple class that is used to read a sequence of characters. It has a simple function read that reads a character, another read which reads an array of characters, and a readLine() function which reads a line. Example: import java.io.*; import java.io.BufferedReader; import java.io.InputStreamReader; class Test { public static void main(String[] args) { // creating the instance of class BufferedReader BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); String name; try { System.out.println("Enter your name"); name = reader.readLine(); // taking string input System.out.println("Name=" + name); } catch (Exception e) { } } } Department of Information Technology 75 Using Scanner Class for Taking Input It is an advanced version of BufferedReader which was added in later versions of Java. The scanner can read formatted input. It has different functions for different types of data types. The scanner is much easier to read as we don’t have to write throws as there is no exception thrown by it. It was added in later versions of Java It contains predefined functions to read an Integer, Character, and other data types as well Syntax of Scanner class: Scanner scn = new Scanner(System.in); To use the Scanner we need to import the Scanner class from the util package as: import java.util.Scanner; Inbuilt Scanner functions are as follows: Integer: nextInt() Float: nextFloat() String : next() and nextLine() Department of Information Technology 76 Using Scanner Class for Taking Input Example // Scanner Class to take input import java.io.*; import java.util.Scanner; // Driver Class class Test{ // main function public static void main(String[] args) { // creating the instance of class Scanner Scanner obj = new Scanner(System.in); String name; int rollno; float marks; System.out.println("Enter your name"); // taking string input name = obj.nextLine(); System.out.println("Enter your rollno"); // taking integer input rollno = obj.nextInt(); System.out.println("Enter your marks"); // taking float input marks = obj.nextFloat(); // printing the output System.out.println("Name=" + name); System.out.println("Rollno=" + rollno); System.out.println("Marks=" + marks); } } Department of Information Technology 77

Use Quizgecko on...
Browser
Browser