Top Banner
Programming Language-II EEE-180 M. Ferdous Rahman Palash Lecturer Cell: 01719783378 Department of Computer Science & Engineering Lecture – 01 Date: 06- 06-2013 What is programming? Computer program is a set of instructions that guide a computer to execute a particular task. It is like a recipe for a cook in making a particular dish. The recipe contains a list of ingredients called the data or variables, and a list of steps that guide the computer what to do with the data. So programming is the technique of making a computer to perform something you want to do. Programming or coding is a language that is used by operating systems to perform the task. We know computer understands binary languages with digits 1s and 0s. These binary languages are difficult to understand by human; so we generally use an intermediate language instead of binary language. Again the program uses high-level language that is interpreted into bytes that the computer understands. So a programmer writes a source code and uses a tool or interpreter that allows the computer to read, translate and execute the programs to perform a function. Today there are different user friendly and easily understandable languages supporting different styles of programming. Some of the computer languages are like formula translation (FORTRAN), C, C+ +, PASCAL, BASIC, Java, C sharp(C#) and many other high-level languages. Further an interpretable p-code or byte code is generated in case some advanced languages like Java.
30

Programming

Dec 19, 2022

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Programming

Programming Language-IIEEE-180

M. Ferdous Rahman PalashLecturer

Cell: 01719783378Department of Computer Science & Engineering

Lecture – 01 Date: 06-06-2013

What is programming?

Computer program is a set of instructions that guide a computerto execute a particular task. It is like a recipe for a cook inmaking a particular dish. The recipe contains a list ofingredients called the data or variables, and a list of stepsthat guide the computer what to do with the data. So programmingis the technique of making a computer to perform something youwant to do.

Programming or coding is a language that is used by operatingsystems to perform the task. We know computer understands binarylanguages with digits 1s and 0s. These binary languages aredifficult to understand by human; so we generally use anintermediate language instead of binary language. Again theprogram uses high-level language that is interpreted into bytesthat the computer understands. So a programmer writes a sourcecode and uses a tool or interpreter that allows the computer toread, translate and execute the programs to perform a function.

Today there are different user friendly and easily understandablelanguages supporting different styles of programming. Some of thecomputer languages are like formula translation (FORTRAN), C, C++, PASCAL, BASIC, Java, C sharp(C#) and many other high-levellanguages. Further an interpretable p-code or byte code isgenerated in case some advanced languages like Java.

Page 2: Programming

These languages enable one to create and perform various kinds ofapplications. However, in the whole process of programming it isimportant to understand that a program written in any of thehigh-level languages needs to be converted to machine language torun on a computer. This conversion is done with a complier or aninterpreter. In all kinds of programming languages a complier andif required an interpreter is available. But the basic differencebetween these two is that the complier converts the entireprogram into machine code. An interpreter, on the other hand,converts one statement at a time to machine language and executesit.

The most important aspect of programming is to analyze and adoptspecific solution while solving any problem. This needs aprogramming approach that defines the modularity of program thatone writes and how it is related to others in an application.Basically there are two different programming approaches;procedure oriented and object oriented. The procedure orientedprogramming (POP) approach focuses on creating and orderingprocedures or a block of code keeping in mind to accomplish aspecific job. The key features of this kind of approach are: useof procedures, sequencing of procedures and sharing global data.

However, in case of the object oriented programming (OOP)approach the focus is totally towards identifying objects or dataand not on creative activities. Unlike the procedure orientedprogramming approach where a peace of code uses data, the object-oriented approach the data uses a peace of code to execute tasks.Principal features of the object-oriented approach are: dataclassification into classes and objects, data encapsulation,abstraction, inheritance, and polymorphism. This kind of approachprovides a realistic representation, flexibility to change anddata security. Now a days most of the high level programminglanguages such as Java, C#, C++, and Visual Basic are based onobject oriented approach.

Programming Languages

Computers speak one language: binary. Binary (or base-2) is anumber system which is composed of only the two numbers, 0 and 1.

Page 3: Programming

Compare that with our decimal number system (or base-10), whichis composed of the ten numbers in the set 0 through 9. Incomputer language, strings of zeroes and ones have meaning. Eachzero or one represents one bit. Eight bits together represent onebyte. While it's probably possible to write programs in binary,it wouldn't be very easy, to say the least. That's whyprogramming languages were created.

Machine Language

Machine languages are just one step above writing in binary. Theyhave a very small set of instructions that represent basic"tasks" to the computer, such as "add", "subtract", "read", etc.Because the instructions are so elementary, it would take a longtime to tell the computer to do something as simple as print asentence. Machine languages are also written for specific typesof computers, so your machine language program on your Windows PCwould not work on your friend's Mac. So machine language programsare neither time efficient, nor portable. To solve some of theseproblems, high-level programming languages were created.

High-Level Languages

High level languages often have keywords that look like Englishwords or phrases and typically have meaning similar to theirEnglish language counterparts. For instance, the BASICprogramming language uses the keyword "goto", which tells thecomputer to go to a specific line in the program and execute thatline. As you can probably tell from that example, each keyword ina high-level language often represents several machineinstructions, which can make programming much easier. But how dowe get from high-level languages to machine languages? And whatabout the several different machine languages? That's wherecompilers come in.

Page 4: Programming

Compilers

Programs written in high-level languages have to be compiled, ortranslated into machine language, before they can be understoodby a computer. Different types of computers "speak" differentmachine languages; therefore each high-level language must have aseparate compiler for each type of computer. And very oftenprograms must still be partially rewritten before being compiledinto different machine languages. This can be inconvenient andoften results in a delay in applications being available forcertain platforms, such as Macintosh. Java was created, in part,to address this issue.

What is OOP?

OOP means Object Oriented Programming. It organizes a programaround its data, objects and a set of well defined interfaces tothat data. An object-oriented program can be characterized asdata controlling access to code. This is a technique used tocreate programs around the real world entities. In OOPsprogramming model, programs are developed around objects and datarather than actions and logics. In OOPs, every real life objecthas properties and behavior. This feature is achieved in javathrough the class and object creation. They contain properties(variables of some type) and behavior (methods). OOPs providebetter flexibility and compatibility for developing largeapplications.

In Java generally you can make three kinds of programs:

1. Console mode Application2. GUI Application (Graphical User Interface)3. Applet

Primitive data types:

Java data type divided into two categories:

1. Primitive types

Page 5: Programming

2. Reference types

There are eight kinds of primitive data types in java:

Types Contains Sizebyte Signed integer 8 bit

short Signed integer 16 bit

char Unsigned Unicode character

16 bit

int Signed integer 32 bit

long Signed integer 64 bit

float Single-precision IEEE standard

32 bit

double Double-precision IEEE 64 bit

boolean True or false 8 bit

Compiler of java

Before the Java virtual machine (JVM) can run a Java program, theprogram's Java source code must be compiled into byte-code usingthe javac compiler. Java byte-code is a platform independentversion of machine code; the target machine is the Java VM ratherthan the underlying architecture.

Compiling a java program is an action where the Java Compilerscans through a java program checking it for syntacticalcorrectness and generates the byte-code (the system recognizableform) of the class so that the program can be executed.

How it works…!

Page 6: Programming

Java virtual machine (JVM)

A Java virtual machine (JVM), an implementation of the JavaVirtual Machine Specification, interprets compiled Java binarycode (called byte code) for a computer's processor (or "hardwareplatform") so that it can perform a Java program's instructions.Java was designed to allow application programs to be built thatcould be run on any platform without having to be rewritten orrecompiled by the programmer for each separate platform. A Javavirtual machine makes this possible because it is aware of thespecific instruction lengths and other particularities of theplatform.

Variable:

A typical program uses various values and these values keepchanging while the program is running. For example, you create a

Page 7: Programming

program that is used to perform calculations; the values enteredby one user will obviously be different from the values enteredby another user. This also means that, when creating the program,you cannot know all possible values that will be entered in yourprogram. You should still be able to manage the values that theusers will eventually enter in your program. Since the valuesentered in a reserved memory area change regularly, they arecalled variables because neither you nor the compiler can predictall possible values that would be used.

Data Types

When declaring a variable, besides its name, we must provide thetype of information that the variable will hold. The role of thistype is to tell the compiler how much memory will be needed tostore the value(s) of that variable. Since our program is not theonly one used in the computer, memory has to be effectivelymanaged.

The type of value that a variable will hold is called a data type.

Double

This means that the largest value that a double can store.

Boolean

A Boolean value is one with two choices: true or false, yes or no, 1 or 0. In Java, there is a variable type for Boolean values:

boolean user = true;

So instead of typing int or double or string, you just typeboolean (with a lower case "b"). After the name of you variable,you can assign a value of either true or false. Notice that theassignment operator is a single equals sign ( = ). If you want to

Page 8: Programming

check if a variable "has a value of" something, you need twoequal signs ( = =).

boolean user = true;

if ( user == true) {System.out.println("it's true");}else {System.out.println("it's false");}

So the first IF Statement checks if the user variable has a valueof true. The else part checks if it is false. You don't need tosay "else if ( user = = false)". After all, if something is nottrue then it's false. So you can just use else: there's only twochoices with boolean values.

null

Null is a value that any variable can have. It means the absenceof a value. However, null can only be assigned to objectreference variables; attempting to execute a method on a nullvariable will cause the JVM to throw a NullPointerError.

Operators

Java provides a rich set of operators to manipulate variables. Wecan divide all the Java operators into the following groups:

Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Misc Operators

Page 9: Programming

Assignment Operator

Assignment operator is the most common operator almost used withall programming languages. It is represented by "=" symbol inJava which is used to assign a value to a variable lying to theleft side of the assignment operator. But, If the value alreadyexists in that variable then it will be overwritten by theassignment operator (=). This operator can also be used to assignthe  references to the objects. Syntax of using the assignmentoperator is:

<variable> = <expression>;

For example:

 int counter = 1; String name = "Nisha"; boolean rs = true; Shape s1 = new Shape(); // creates new object Shape s2 = s1;   //assigning the reference of  s1 to s2 counter = 5;       // previous value is overwritten

The Arithmetic OperatorsThe Java programming language provides operators that performaddition, subtraction, multiplication, and division. There's agood chance you'll recognize them by their counterparts in basic

Page 10: Programming

mathematics. The only symbol that might look new to you is "%",which divides one operand by another and returns the remainder asits result.

+ additive operator (also used for String concatenation)- subtraction operator* multiplication operator/ division operator% remainder operator

The following program, ArithmeticDemo, tests the arithmetic operators.class ArithmeticDemo {

public static void main (String[] args){ // result is now 3 int result = 1 + 2; System.out.println(result);

// result is now 2 result = result - 1; System.out.println(result);

// result is now 4 result = result * 2; System.out.println(result);

// result is now 2 result = result / 2; System.out.println(result);

// result is now 10 result = result + 8;

Page 11: Programming

// result is now 3 result = result % 7; System.out.println(result); }}We can also combine the arithmetic operators with the simpleassignment operator to create compound assignments. For example,x+=1; and x=x+1; both increment the value of x by 1.

The + operator can also be used for concatenating (joining) twostrings together, as shown in the following ConcatDemo program:

class ConcatDemo { public static void main(String[] args){ String firstString = "This is"; String secondString = " a concatenated string."; String thirdString = firstString+secondString; System.out.println(thirdString); }}

By the end of this program, the variable thirdString contains"This is a concatenated string.", which gets printed to standardoutput.

The Unary Operators

The unary operators require only one operand; they performvarious operations such as incrementing/decrementing a value byone, negating an expression, or inverting the value of a boolean.

+ Unary plus operator; indicates positive value (numbers are positive without this, however)- Unary minus operator; negates an expression++ Increment operator; increments a value by 1-- Decrement operator; decrements

Page 12: Programming

a value by 1! Logical complement operator; inverts the value of a boolean

The following program, UnaryDemo, tests the unary operators:

class UnaryDemo {

public static void main(String[] args){ // result is now 1 int result = +1; System.out.println(result); // result is now 0 result--; System.out.println(result); // result is now 1 result++; System.out.println(result); // result is now -1 result = -result; System.out.println(result); boolean success = false; // false System.out.println(success); // true System.out.println(!success); }}

The increment/decrement operators can be applied before (prefix)or after (postfix) the operand. The code result++; and ++result;will both end in result being incremented by one. The onlydifference is that the prefix version (++result) evaluates to theincremented value, whereas the postfix version (result++)evaluates to the original value. If you are just performing asimple increment/decrement, it doesn't really matter whichversion you choose. But if you use this operator in part of alarger expression, the one that you choose may make a significantdifference.

Page 13: Programming

The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:

class PrePostDemo { public static void main(String[] args){ int i = 3; i++; // prints 4 System.out.println(i); ++i; // prints 5 System.out.println(i); // prints 6 System.out.println(++i); // prints 6 System.out.println(i++); // prints 7 System.out.println(i); }}

Logical Operators

Every programming language has its own logical operators, or atleast a way of expressing logic. Java's logical operators aresplit into two subtypes, relational and conditional. We can usethese operators to make your programs much more flexible and

Page 14: Programming

powerful. We'll also get the added benefit of making our codeeven that much easier to read and to write

Relational OperatorsRelational operators are used primarily in if statements, while loops, and on occasion for loops.

Conditional symbols andtheir meanings

Symbol Condition== is equal to!= is not equal to> is greater than< is less than

>= is greater than or equal to

<= is less than or equal to

Here is how it looks like in an if statement:

The if statement is true when the variable num is not equal to 3.Otherwise, the condition is true.

Conditional Operators

There are four logical operators in Java. Conditional operators,like their relational counterparts, are also mostly used in ifstatements, while loops, and for loops.

Here's the table of logical operators:

Page 15: Programming

Conditional symbols and their meanings

Symbol Condition

&& AND

|| OR

! NOT

And Operator

If we wanted our program to output "You Win!" when num1 is equalto 3 and num2 is equal to 5.

First, Java will look at the first if statement. Then, if it'strue, it will go on to the second if statement. If that one isalso true, then it will print out "You Win!" on the screen. Seemssimple enough.

But there has to be a better way than putting an if statement inside of another if statement!

There is. Enter the AND operator.

Page 16: Programming

Here we see how much cleaner that code looks? It even soundsbetter when we say it in English. If num1 is equal to 3 and num2is equal to 5, then output "You win!". This is much, much better.

Or Operator

Up until this point, it was ridiculously difficult to make abunch of if statements so that the program will execute a pieceof code if only one out of several conditions is true. The ORoperator allows just this, the ability to have an if statement betrue if only one out of several conditions is met.

Here we see how this example of code is different from theprevious? The code will run if num1 is equal to 3 OR num2 isequal to 5. Only one of them has to be true for that to happen.If both are true, that's fine also. The only time that ifstatement will be false is when num1 is not equal to 3 AND num2is not equal to 5.

Learning about the logical operators means that we will need tobrush up on our logic. The easiest way to put it is like this:

AND is when you need everything to be true

OR is when you need only one thing to be true

Not Operator

The not operator is probably the easiest to understand. It issimply the opposite of what the condition says.

Page 17: Programming

Notice how we needed to an extra set of parenthesis. Basicallythe if statement says if NOT num1 is equal to 3. In other words,if num1 is not equal to 3. Here we see how that works.

This is the exact same thing. This is an easier way to use "is not equal to".

First of all, we using a boolean variable. We created one and setit to true. Next we use an if statement. In English it reads, "ifnot flag". Remember that flag is equal to true, so the Englishbecomes, "if not true".

"if not true" is asking if the variable flag is not true,otherwise known as false. If flag is false, Java will display"You win!". Flag is set to true, so that code will not execute.If we are following along (which I HIGHLY recommend), then trytaking out the NOT operator and running the code to see that Javawill display "You win!" now that the if statement is checking ifflag is true.

Here are some necessary operators of java:

Operator Meaning Example Evaluati

Page 18: Programming

on+ Addition c = c + b- Subtraction c = a - b* Multiplication c = c * b/ Division c = c / b% Modulus c = c % b++ Increment a++

(a+1)-- Decrement b--

(b-1)+= Addition and

assignmentc + = a c = c+a

-= Subtraction and assignment

c - = a c = c-a

*= Multiplicationand assignment

c *= a c = c*a

/= Division and assignment

c /= a c = c / a

%= Modulus and assignment

c %= a c = c % a

== Equal to a == b!= Not equal to a !=b> Greater than a>b< Less than a<b>= Greater than

or Equal to a>=b

<= Less than or Equal to

a<=b

& Logical AND c1 & c2&& Logical OR c1 | c2&= Bitwise AND

assignmentb & = a b = b &

a

Page 19: Programming

Java is an Object Oriented Language. As a language that has theObject Oriented feature Java supports the following fundamentalconcepts:

Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method Message Parsing

Object & Class

Object - Objects have states and behaviors. Example: A doghas states-color, name, breed as well as behaviors -wagging,barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue printthat describe the behaviors/states that object of its typesupport.

Objects in Java:

Let us now look deep into what are objects. If we consider thereal-world we can find many objects around us, Cars, Dogs, Humansetc. All these objects have a state and behavior.

If we consider a dog then its state is: Name, breed, color, andthe behavior is: barking, wagging, running

Page 20: Programming

If you compare the software object with a real world object, theyhave very similar characteristics.

Software objects also have a state and behavior. A softwareobject's state is stored in fields and behavior is shown viamethods.

So in software development methods operate on the internal stateof an object and the object-to-object communication is done viamethods.

Classes in Java:

A class is a blue print from which individual objects are created.

A sample of a class is given below:

public class

Dog{

String

breed;

int age;

String

color;

void

barking(){

}

Page 21: Programming

void

hungry(){

}

void

sleeping(){

}

}

A class can contain any of the following variable types.

Local variables. Variables defined inside methods,constructors or blocks are called local variables. Thevariable will be declared and initialized within the methodand the variable will be destroyed when the method hascompleted.

Instance variables. Instance variables are variables withina class but outside any method. These variables areinstantiated when the class is loaded. Instance variablescan be accessed from inside any method, constructor orblocks of that particular class.

Class variables. Class variables are variables declared within a class, outside any method, with the static keyword.

A class can have any number of methods to access the value ofvarious kind of methods. In the above example, barking(),hungry() and sleeping() are variables.

Below mentioned are some of the important topics that need to bediscussed when looking into classes of the Java Language.

Constructors:

Page 22: Programming

When discussing about classes one of the most important sub topicwould be constructors. Every class has a constructor. If we donot explicitly write a constructor for a class the java compilerbuilds a default constructor for that class.

Each time a new object is created at least one constructor willbe invoked. The main rule of constructors is that they shouldhave the same name as the class. A class can have more than oneconstructor.

Example of a constructor is given below:

class Puppy{ public puppy(){ }

public puppy(String name){ // This constructor has one parameter, name. }}

Java also supports Singleton Classes where you would be able tocreate only one instance of a class.

Creating an Object:

As mentioned previously a class provides the blueprints forobjects. So basically an object is created from a class. In javathe new key word is used to create new objects.

There are three steps when creating an object from a class:

Declaration: A variable declaration with a variable namewith an object type.

Page 23: Programming

Instantiation: The 'new' key word is used to create theobject.

Initialization: The 'new' keyword is followed by a call o aconstructor. This call initializes the new object.

Example of creating an object is given below:

class Puppy{ public Puppy(String name){ // This constructor has one parameter, name. System.out.println("Passed Name is:" + name ); } public static void main(String []args){ // Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy"); }}

If we compile and run the above program then it would producefollowing result:

Passed Nameis :tommy

Accessing Instance Variables and Methods:

Instance variables and methods are accessed via created objects.To access an instance variable the fully qualified path should beas follows:

Page 24: Programming

/* First create an object */ObjectReference = new Constructor();

/* Now call a variable as follows*/ObjectReference.variableName;

/* Now you can call a class method as follows */ObjectReference.MethodName();

Example:

This example explains how to access instance variables andmethods of a class:

class Puppy{ int puppyAge;

public Puppy(String name){ // This constructor has one parameter, name. System.out.println("Passed Name is :" + name );

Page 25: Programming

} public setAge( int age ){ puppyAge = age; }

public getAge( ){ System.out.println("Puppy's age is :" + puppyAge ); return puppyAge; } public static void main(String []args){ /* Object creation */ Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */ myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */ myPuppy.getAge( );

/* You can access instance variable as follows as well */ System.out.println("Variable Value :" + myPuppy.puppyAge ); }}

Page 26: Programming

If we compile and run the above program then it would producefollowing result:

Passed Name

is :tommy

Puppy's age is :2

Variable Value :2

Declaration rules:

There can be only one public class per source file.

A source file can have multiple non public classes.

The public class name should be the name of the source file

as well which should be appended by .java at the end. For

example : The class name is . public class Employee{} Then the

source file should be as Employee.java.

If the class is defined inside a package, then the package

statement should be the first statement in the source file.

If import statements are present then they must be written

between the package statement and the class declaration. If

there are no package statements then the import statement

should be the first line in the source file.

Import and package statements will imply to all the classes

present in the source file. It is not possible to declare

different import and/or package statements to different

classes in the source file.

Page 27: Programming

Classes have several access levels and there are different types

of classes; abstract classes, final classes etc. I will be

explaining about all these in the access modifiers chapter.

Apart from the above mentioned types of classes, Java also has

some special classes called Inner classes and Anonymous classes.

In simple it is a way of categorizing the classes and interfaces. When developing

applications in Java, hundreds of classes and interfaces will be written, therefore

categorizing these classes is a must as well as makes life much easier.

A Simple Case Study:

For our case study we will be creating two classes. They are Employee and EmployeeTest.

First open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now save thissource file with the name Employee.java.

The Employee class has four class variables name, age, designation and salary. The class has one explicitly defined constructor which takes a parameter.

import java.io.*;public class Employee{ String name; int age; String designation; double salary;

// This is the constructor of the class Employee public Employee(String name){ this.name = name; }

Page 28: Programming

// Assign the age of the Employee tothe variable age. public void empAge(int empAge){ age = empAge; } /* Assign the designation to the variable designation.*/ public void empDesignation(String empDesig){ designation = empDesig; } /* Assign the salary to the variable

salary.*/ public void empSalary(double empSalary){ salary = empSalary; } /* Print the Employee details */ public void printEmployee(){ System.out.println("Name:"+ name ); System.out.println("Age:" + age ); System.out.println("Designation:" + designation ); System.out.println("Salary:" + salary); }}

As mentioned previously in this tutorial processing starts from the main method. Therefore in-order for us to run this Employee class there should be main method and objects should be created. We will be creating a separate class for these tasks.

Given below is the EmployeeTest class which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.

Page 29: Programming

Save the following code in EmployeeTest.java file

import java.io.*;public class EmployeeTest{ public static void main(String args[]){ /* Create two objects using constructor */ Employee empOne = new Employee("James Smith"); Employee empTwo = new Employee("Mary Anne");

// Invoking methods for each object created empOne.empAge(26); empOne.empDesignation("Senior Software Engineer"); empOne.empSalary(1000); empOne.printEmployee();

empTwo.empAge(21); empTwo.empDesignation("Software Engineer"); empTwo.empSalary(500); empTwo.printEmployee(); }}

Now compile both the classes and then run EmployeeTest to see the result as follows:

C :> javac Employee.javaC :> vi EmployeeTest.javaC :> javac EmployeeTest.javaC :> java EmployeeTestName:James SmithAge:26

Page 30: Programming

Designation:Senior Software EngineerSalary:1000.0Name:Mary AnneAge:21Designation:Software EngineerSalary:500.0