Programming Book PDF
Document Details
Uploaded by ReplaceableAstatine
Higher Institute of Computer Science and Information Systems
Dr. Marwa O. Al Enany
Tags
Summary
This document is a set of lecture notes on computer programming, from the Higher Institute of Computer Science and Information Systems. The notes cover the principles of programming, including different types of programming languages (high-level languages and assembly languages), and essential hardware concepts.
Full Transcript
Ministry of Higher Education Higher Institute of Computer Science and Information Systems Lectures Notes in: Computer Programing Prepared by Dr. Marwa O. Al Enany I I Chapt...
Ministry of Higher Education Higher Institute of Computer Science and Information Systems Lectures Notes in: Computer Programing Prepared by Dr. Marwa O. Al Enany I I Chapter 1: Principles of Programming Chapter 1: Principles of programming 1.1 Introduction A computer is an electronic device that stores and processes data. A computer includes both hardware and software. In general, hardware comprises the visible, physical elements of the computer, and software provides the invisible instructions that control the hardware and make it perform specific tasks. Knowing computer hardware isn’t essential to learning a programming language, but it can help you better understand the effects that a program’s instructions have on the computer and its components. A computer consists of the following major hardware: A central processing unit (CPU) Memory (main memory) Storage devices (such as disks and CDs) Input devices (such as the mouse and keyboard) Output devices (such as monitors and printers) Communication devices (such as modems and network interface cards). A computer’s components are interconnected by a subsystem called a bus. You can think of a bus as a sort of system of roads running among the computer’s components; data and power travel along the bus from one part of the computer to another. In personal computers, the bus is built into the computer’s motherboard, which is a circuit case that connects all of the parts of a computer together. 1 Chapter 1: Principles of Programming A computer is really nothing more than a series of switches. Each switch exists in two states: on or off. Storing information in a computer is simply a matter of setting a sequence of switches on or off. If the switch is on, its value is 1. If the switch is off, its value is 0. These 0s and 1s are interpreted as digits in the binary number system and are called bits (binary digits). The minimum storage unit in a computer is a byte. A byte is composed of eight bits. A small number such as 3 can be stored as a single byte. To store a number that cannot fit into a single byte, the computer uses several bytes. A kilobyte (KB) is about 1,000 bytes. A megabyte (MB) is about 1 million bytes. A gigabyte (GB) is about 1 billion bytes. A terabyte (TB) is about 1 trillion bytes. 1.2 Programming Languages Computer programs, known as software, are instructions that tell a computer what to do. Computers do not understand human languages, so programs must be written in a language a computer can use. There are hundreds of programming languages, and they were developed to make the programming process easier for people. However, all 2 Chapter 1: Principles of Programming programs must be converted into the instructions the computer can execute. Machine Language A computer’s native language, which differs among different types of computers, is its machine language—a set of built-in primitive instructions. These instructions are in the form of binary code, so if you want to give a computer an instruction in its native language, you have to enter the instruction as binary code. For example, to add two numbers, you might have to write an instruction in binary code, like this: 1101101010011010 Assembly Language Programs written in machine language are very difficult to read and modify. For this reason, assembly language was created in the early days of computing as an alternative to machine languages. Assembly language uses a short descriptive word, known as a mnemonic, to represent each of the machine- language instructions. For example, the mnemonic add typically means to add numbers and sub means to subtract numbers. To add the numbers 2 and 3 and get the result, you might write an instruction in assembly code like this: add 2, 3, result. 3 Chapter 1: Principles of Programming Assembly languages were developed to make programming easier. However, because the computer cannot execute assembly language, another program—called an assembler—is used to translate assembly-language programs into machine code. Writing code in assembly language is easier than in machine language. However, it is still tedious to write code in assembly language. An instruction in assembly language essentially corresponds to an instruction in machine code. Writing in assembly requires that you know how the CPU works. Assembly language is referred to as a low-level language, because assembly language is close in nature to machine language and is machine dependent. High-Level Language In the 1950s, a new generation of programming languages known as high-level languages emerged. They are platform independent, which means that you can write a program in a high level language and run it in different types of machines. High-level languages are English-like and easy to learn and use. The instructions in a high-level programming language are called statements. Here, for example, is a high- level language statement that computes the area of a circle with a radius of 5: area = 5 * 5 * 3.14159; A program written in a high-level language is called a source program or source code. Because a computer cannot execute a source program, a source program must be translated into machine code for execution. 4 Chapter 1: Principles of Programming The translation can be done using another programming tool called an interpreter or a compiler. An interpreter reads one statement from the source code, translates it to the machine code or virtual machine code, and then executes it right away. Note that a statement from the source code may be translated into several machine instructions. A compiler translates the entire source code into a machine-code file, and the machine-code file is then executed. 1.3 Operating Systems The operating system (OS)manages and controls a computer’s activities. The popular operating systems for general-purpose computers are Microsoft Windows, Mac OS, and Linux. Application programs, such as a Web browser or a word processor, cannot run unless an operating system is installed and running on the computer. The major tasks of an operating system are as follows: Controlling and monitoring system activities Allocating and assigning system resources Scheduling operations 5 Chapter 1: Principles of Programming 1.4 Software Development Process The software development life cycle is a multistage process that includes requirements specification, analysis, design, implementation, testing, deployment, and maintenance. Developing a software product is an engineering process. Software products, no matter how large or how small, have the same life cycle as in the following figure: 1. Requirements specification is a formal process that seeks to understand the problem that the software will address and to document in detail what the software system needs to do. This phase involves 6 Chapter 1: Principles of Programming close interaction between users and developers. Most of the examples in the real world problems are not always well defined. Developers need to work closely with their customers (the individuals or organizations that will use the software) and study the problem carefully to identify what the software needs to do. 2. System analysis seeks to analyze the data flow and to identify the system’s input and output. When you do analysis, it helps to identify what the output is first, and then figure out what input data you need in order to produce the output. 3. System design is to design a process for obtaining the output from the input. This phase involves the use of many levels of abstraction to break down the problem into manageable components and design strategies for implementing each component. You can view each component as a subsystem that performs a specific function of the system. 4. Implementation involves translating the system design into programs. Separate programs are written for each component and then integrated to work together. This phase requires the use of a programming language such as Java. The implementation involves coding, self testing, and debugging (that is, finding errors, called bugs, in the code). 7 Chapter 1: Principles of Programming 5. Testing ensures that the code meets the requirements specification and weeds out bugs. An independent team of software engineers not involved in the design and implementation of the product usually conducts such testing. 6. Deployment makes the software available for use. Depending on the type of software, it may be installed on each user’s machine or installed on a server accessible on the Internet. 7. Maintenance is concerned with updating and improving the product. A software product must continue to perform and improve in an ever-evolving environment. This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes. 1.5 Java Programming language Java is popular high-level, class-based object oriented programming language originally developed by Sun Microsystems and released in 1995. Currently Java is owned by Oracle and more than 3 billion devices run Java. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Java is used to develop numerous types of software applications like Mobile apps, Web apps, Desktop apps, Games and much more. Java is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Software Development Domain. If you will 8 Chapter 1: Principles of Programming conduct a survey about the best programming language, Java is sure to come up. Java is fairly easy to learn, so if you are starting to learn any programming language then Java could be your great choice. There is also plenty of Java tools that make it easy for developers and beginners to use. There are many other good reasons which makes Java as the first choice of any programmer: Java is Open Source which means its available free of cost. Java is simple and so easy to learn Java is much in demand and ensures high salary Java has a large vibrant community Java has powerful development tools Java is platform independent 1.5.1 Java Applications Mobile applications (specially Android apps) Desktop applications Web applications Web servers and application servers Games Database connection And much, much more! The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. 9 Chapter 1: Principles of Programming 1.5.2 Java Terminology Before learning Java, one must be familiar with these common terms of Java. 1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution phases of a program. They are written, compile and run the program. Writing a program is done by a java programmer like you and me. The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java development kit (JDK). It takes the Java program as input and generates bytecode as output. In the Running phase of a program, JVM executes the bytecode generated by the compiler. Now, we understood that the function of Java Virtual Machine is to execute the bytecode produced by the compiler. Every Operating System has a different JVM but the output they produce after the execution of bytecode is the same across all the operating systems. This is why Java is known as a platform- independent language. 2. Bytecode in the Development Process: As discussed, the Javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. It is saved as.class file by the compiler. To view the bytecode, a disassembler like javap can be used. 10 Chapter 1: Principles of Programming 3. Java Development Kit(JDK): While we were using the term JDK when we learn about bytecode and JVM. So, as the name suggests, it is a complete Java development kit that includes everything including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program to execute in java, we need to install JDK on our computer in order to create, compile and run the java program. 4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows the java program to run, however, we cannot compile it. JRE includes a browser, JVM, applet support, and plugins. For running the java program, a computer needs JRE. 5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a program called Garbage Collector. Garbage Collectors can recollect the objects that are not referenced. So Java makes the life of a programmer easy by handling memory management. However, programmers should be careful about their code whether they are using objects that have been used for a long time. Because Garbage cannot recover the memory of objects being referenced. 11 Chapter 1: Principles of Programming 6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for.class files to load. By default, JDK provides many libraries. 1.5.3 Primary/Main Features of Java 1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode generated by the compiler. This bytecode can run on any platform be it Windows, Linux, or macOS which means if we compile a program on Windows, then we can run it on Linux and vice versa. Each operating system has a different JVM, but the output produced by all the OS is the same after the execution of the bytecode. That is why we call java a platform- independent language. 2. Object-Oriented Programming Language: Organizing the program in the terms of a collection of objects is a way of object-oriented programming, each of which represents an instance of the class. The four main concepts of Object-Oriented programming are: Abstraction Encapsulation Inheritance Polymorphism 12 Chapter 1: Principles of Programming 3. Simple: Java is one of the simple languages as it does not have complex features like pointers, operator overloading, multiple inheritances, and Explicit memory allocation. 4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort into checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not easy to detect by another programming language. The main features of java that make it robust are garbage collection, Exception Handling, and memory allocation. 5. Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack corruption or buffer overflow are impossible to exploit in Java. Also, java programs run in an environment that is independent of the os(operating system) environment which makes java programs more secure. 6. Distributed: We can create distributed applications using the java programming language. Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java programs can be easily distributed on one or more systems that are connected to each other through an internet connection. 7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two 13 Chapter 1: Principles of Programming or more parts of a program for maximum utilization of the CPU. 8. Portable: As we know, java code written on one machine can be run on another machine. The platform-independent feature of java in which its platform-independent bytecode can be taken to any platform for execution makes java portable. 9. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime and at some times java uses Just In Time (JIT) compiler where the compiler compiles code on- demand basics where it only compiles those methods that are called making applications to execute faster. 10. Dynamic flexibility: Java being completely object- oriented gives us the flexibility to add classes, new methods to existing classes, and even create new classes through sub-classes. Java even supports functions written in other languages such as C, C++ which are referred to as native methods. 11. Sandbox Execution: Java programs run in a separate space that allows user to execute their applications without affecting the underlying system with help of a bytecode verifier. Bytecode verifier also provides additional security as its role is to check the code for any violation of access. 12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file that corresponds to our applications(program) but contains code in binary format. It provides ease t architecture-neutral ease as 14 Chapter 1: Principles of Programming bytecode is not dependent on any machine architecture. It is the primary reason java is used in the enterprising IT industry globally worldwide. 13. Power of compilation and interpretation: Most languages are designed with the purpose of either they are compiled language or they are interpreted language. But java integrates arising enormous power as Java compiler compiles the source code to bytecode and JVM executes this bytecode to machine OS-dependent executable code. To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following : Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans − A Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html. Eclipse − A Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/. 1.6 Java first program In Java, every application begins with a class name, and that class must match the filename. Let's create our first Java file, called Main.java, which can be done in any text editor (like Notepad). The file should 15 Chapter 1: Principles of Programming contain a "Hello World" message, which is written with the following code: public class Main { public static void main(String[] args) { System.out.println("Hello World"); } } We break the process of programming in Java into three steps: 1. Create the program by typing it into a text editor and saving it to a file named, say, MyProgram.java. 2. Compile it by typing "javac MyProgram.java" in the terminal window. 3. Execute (or run) it by typing "java MyProgram" in the terminal window. The first step creates the program; the second translates it into a language more suitable for machine execution (and puts the result in a file named MyProgram.class); the third actually runs the program. A program is nothing more than a sequence of characters, like a sentence, a paragraph, or a poem. To create one, we need only define that sequence characters using a text editor in the same way as we do for email. HelloWorld.java is an example program. Type these character into your text editor and save it into a file named HelloWorld.java. 16 Chapter 1: Principles of Programming public class HelloWorld { public static void main(String[] args) { // Prints "Hello, World" in the terminal window. System.out.println("Hello, World"); } } A compiler is an application that translates programs from the Java language to a language more suitable for executing on the computer. It takes a text file with the.java extension as input (your program) and produces a file with a.class extension (the computer- language version). To compile HelloWorld.java type the boldfaced text below at the terminal. (We use the % symbol to denote the command prompt, but it may appear different depending on your system.) % javac HelloWorld.java If you typed in the program correctly, you should see no error messages. Otherwise, go back and make sure you typed in the program exactly as it appears above. Executing (or running) a Java program. Once you compile your program, you can execute it. This is the exciting part, where the computer follows your instructions. To run the HelloWorld program, type the following in the terminal window: % java HelloWorld If all goes well, you should see the following response Hello, World 17 Chapter 1: Principles of Programming Example explained:: class keyword is used to declare a class in Java. public keyword is an access modifier that represents visibility. It means it is visible to all. static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main() method is executed by 18 Chapter 1: Principles of Programming the JVM, so it doesn't require creating an object to invoke the main() method. So, it saves memory. void is the return type of the method. It means it doesn't return any value. main represents the starting point of the program. String[] args or String args[] is used for command line argument. System.out.println() is used to print statement. Here, System is a class, out is an object of the PrintStream class, println() is a method of the PrintStream class. The Main method: Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A class should always start with an uppercase first letter. Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning. The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename. The output should be: Hello World The main() method is required and you will see it in every Java program: public static void main(String[] args) Any code inside the main() method will be executed. For now, just remember that every Java program has a class name which must match the filename, and that every program must contain the main() method. 19 Chapter 1: Principles of Programming Println method: Inside the main() method, we can use the println() method to print a line of text to the screen: public static void main(String[] args) { System.out.println("Hello World"); } Statement terminator: Every statement in Java ends with a semicolon (;). For example: System.out.println("Hello World"); Blocks: A pair of braces in a program forms a block that groups components of a program. Double Quotes: When you are working with text, it must be wrapped inside double quotations marks "". If you forget the double quotes, an error occurs: Example System.out.println("This sentence will work!"); System.out.println(This sentence will produce an error); You can also use the println() method to print numbers.However, unlike text, we don't put numbers inside double quotes. 20 Chapter 1: Principles of Programming Special Symbols Print Text: you can use the println() method to output values or print text in Java: Example System.out.println("Hello World!"); You can add as many println() methods as you want. Note that it will add a new line for each method: Example System.out.println("Hello World!"); System.out.println("I am learning Java."); Output Hello World! I am learning Java. The Print() Method There is also a print() method, which is similar to println().The only difference is that it does not insert a new line at the end of the output: Example System.out.print("Hello World! "); System.out.print("I will print on the same line."); 21 Chapter 1: Principles of Programming Output Hello World! I will print on the same line. Java Comments: Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Single-line Comments Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by Java (will not be executed). This example uses a single-line comment before a line of code: Example // This is a comment Java Multi-line Comments Multi-line comments start with. Any text between will be ignored by Java. Example 22 Chapter 2: Java Terminologies Chapter 2: Java Terminologies 2.1 Java Variables A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type. A Variable is a name of memory location. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed. Example: int data=50; //Here data is variable A variable must be declared before it can be assigned a value. A variable declared in a method must be assigned a value before it can be used. Whenever possible, declare a variable and assign its initial value in one step. This will make the program easy to read and avoid programming errors. Every variable has a scope. The scope of a variable is the part of the program where the variable can be referenced. After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign (=) is used as the assignment operator. The syntax for assignment statements is as follows: variable = expression; 23 Chapter 2: Java Terminologies An expression represents a computation involving values, variables, and operators that, taking them together, evaluates to a value. For example, consider the following code: You can use a variable in an expression. A variable can also be used in both sides of the = operator. For example, x = x + 1; In this assignment statement, the result of x + 1 is assigned to x. If x is 1 before the statement is executed, then it becomes 2 after the statement is executed. 2.2 Named Constants A named constant is an identifier that represents a permanent value. The value of a variable may change during the execution of a program, but a named constant, or simply constant, represents permanent data that never changes. In our ComputeArea program, p is a constant. If you use it frequently, you don’t want to keep typing 3.14159; instead, you can declare a constant for p. Here is the syntax for declaring a constant: final datatype CONSTANTNAME = value; 24 Chapter 2: Java Terminologies A constant must be declared and initialized in the same statement. The word final is a Java keyword for declaring a constant. For example, 2.3 Types of Variables There are three types of variables in Java: local variable instance variable static variable 25 Chapter 2: Java Terminologies 1) Local Variable A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor, or block. Local variables are implemented at stack level internally. There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use. 2) Instance Variable A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static. It is called an instance variable because its value is instance-specific and is not shared among instances. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared in class level before or after use. 3) Static variable Class variables also known as static variables are declared with the static keyword in a class, but outside 26 Chapter 2: Java Terminologies a method, constructor or a block. A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory. Example to understand the types of variables in java public class A { static int m=100;//static variable void method() { int n=90;//local variable } public static void main(String args[]) { int data=50;//instance variable } }//end of class Java Variable Example: Add Two Numbers public class Simple{ public static void main(String[] args){ int a=10; int b=10; int c=a+b; System.out.println(c); } } Output: 20 Java Variable Example: Overflow class Simple{ public static void main(String[] args){ //Overflow int a=130; 27 Chapter 2: Java Terminologies byte b=(byte)a; System.out.println(a); System.out.println(b); }} Output: 130 -126 Java Variable Example: Adding Lower Type class Simple{ public static void main(String[] args){ byte a=10; byte b=10; //byte c=a+b;//Compile Time Error: because a+b=20 will be int byte c=(byte)(a+b); System.out.println(c); } } Output: 20 2.4 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 data types. Data types in Java are of different sizes and values that can be stored in the variable that is made as per convenience and circumstances to cover up all test 28 Chapter 2: Java Terminologies cases. Java has two categories in which data types are segregated Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double Non-Primitive Data Type or Object Data type: such as String, Array, etc. 1. Primitive Data Types in Java Primitive data are only single values and have no special capabilities. There are 8 primitive data types. They are depicted below in tabular format below as follows: Example Type Description Default Size Range of values Literals boolean true or false false 1 bit true, false true, false twos- byte complement 0 8 bits (none) -128 to 127 integer characters ‘a’, ‘\u0041’, Unicode representation char \u0000 16 bits ‘\101’, ‘\\’, ‘\’, of ASCII values character ‘\n’, ‘β’ 0 to 255 twos- -32,768 to short complement 0 16 bits (none) 32,767 integer 29 Chapter 2: Java Terminologies Example Type Description Default Size Range of values Literals twos- -2,147,483,648 int complement 0 32 bits -2,-1,0,1,2 to intger 2,147,483,647 - 9,223,372,036,85 twos- -2L,- 4,775,808 long complement 0 64 bits to 1L,0L,1L,2L integer 9,223,372,036,85 4,775,807 1.23e100f , - IEEE 754 floating upto 7 decimal float 0.0 32 bits 1.23e-100f , digits point.3f ,3.14F 1.23456e300 IEEE 754 floating upto 16 decimal double 0.0 64 bits d , -123456e- digits point 300d , 1e1d 1. Boolean Data Type Boolean data type represents only one bit of information either true or false which is intended to represent the two truth values of logic and Boolean algebra, but the size of the boolean data type is virtual machine-dependent. Values of type boolean are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code. Syntax: boolean booleanVar; Size: Virtual machine dependent 2. Byte Data Type The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in large arrays. Syntax: byte byteVar; 30 Chapter 2: Java Terminologies Size: 1 byte (8 bits) 3. Short Data Type The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually matters. Syntax: short shortVar; Size: 2 bytes (16 bits) 4. Integer Data Type It is a 32-bit signed two’s complement integer. Syntax: int intVar; Size: 4 bytes ( 32 bits ) 5. Long Data Type The range of a long is quite large. The long data type is a 64-bit two’s complement integer and is useful for those occasions where an int type is not large enough to hold the desired value. The size of the Long Datatype is 8 bytes (64 bits). Syntax: long longVar; 6. Float Data Type The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you need to save memory in large arrays of floating-point numbers. The size of the float data type is 4 bytes (32 bits). Syntax: float floatVar; 31 Chapter 2: Java Terminologies 7. Double Data Type The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type is generally the default choice. The size of the double data type is 8 bytes or 64 bits. Syntax: double doubleVar; 8. Char Data Type The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits). Syntax: char charVar; So, other languages like C/C++ use only ASCII characters, and to represent all ASCII characters 8 bits is enough. But java uses the Unicode system not the ASCII code system and to represent the Unicode system 8 bits is not enough to represent all characters so java uses 2 bytes for characters. Unicode defines a fully international character set that can represent most of the world’s written languages. Example: class GFG { public static void main(String args[]) { char a = 'G'; int i = 89; // use byte and short // if memory is a constraint byte b = 4; // this will give error as number is // larger than byte range // byte b1 = 7888888955; short s = 56; 32 Chapter 2: Java Terminologies // this will give error as number is // larger than short range // short s1 = 87878787878; // by default fraction value // is double in java double d = 4.355453532; float f = 4.7333434f; // need to hold big range of numbers than we need long l = 12121; System.out.println("char: " + a); System.out.println("integer: " + i); System.out.println("byte: " + b); System.out.println("short: " + s); System.out.println("float: " + f); System.out.println("double: " + d); System.out.println("long: " + l); } } Output char: G integer: 89 byte: 4 short: 56 float: 4.7333436 double: 4.355453532 long: 12121 2. Non-Primitive Data Type or Reference Data Types The Reference Data Types will contain a memory address of variable values because the reference types won’t 33 Chapter 2: Java Terminologies store the variable value directly in memory. They are strings, objects, arrays, etc. 1. 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. Unlike C/C++, Java strings are not terminated with a null character. Syntax: “”; Example: // Declare String without using new operator String s = "greetings"; // Declare String using new operator String s1 = new String("greetings"); String Concatenation in Java: In Java, String concatenation forms a new String that is the combination of multiple strings. There are two ways to concatenate strings in Java: 1) String Concatenation by + (String concatenation) operator Java String concatenation operator (+) is used to add strings. For Example: class TestStringConcatenation1{ public static void main(String args[]){ String s="java"+" prog"; System.out.println(s);//java prog } } 34 Chapter 2: Java Terminologies 2) String Concatenation by concat() method The String concat() method concatenates the specified string to the end of current string. Syntax: public String concat(String another) Example: class TestStringConcatenation2{ public static void main(String args[]){ String s1="java"; String s2="prog"; String s3=s1.concat(s2); System.out.println(s3);//java prog } } 2. Class A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: 1. Modifiers: A class can be public or has default access. Refer to access specifiers for classes or interfaces in Java 2. Class name: The name should begin with an initial letter (capitalized by convention). 3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword 35 Chapter 2: Java Terminologies extends. A class can only extend (subclass) one parent. 4. 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. 5. Body: The class body is surrounded by braces, { }. 3. Object An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of : 1. State: It is represented by the 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 to other objects. 3. Identity: It gives a unique name to an object and enables one object to interact with other objects. 4. Interface Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). 36 Chapter 2: Java Terminologies Interfaces specify what a class must do and not how. It is the blueprint of the class. An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement. If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract. A Java library example is Comparator Interface. If a class implements this interface, then it can be used to sort a collection. 5. Array An Array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. The following are some important points about Java arrays. In Java, all arrays are dynamically allocated. Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using size. 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. 37 Chapter 2: Java Terminologies 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. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable 2.5 Java Scanner Class Java Scanner class allows the user to take input from the console. It belongs to java.util package. It is used to read the input of primitive types like int, double, long, short, float, and byte. It is the easiest way to read input in Java program. Syntax: Scanner sc=new Scanner(System.in); The above statement creates a constructor of the Scanner class having System.inM as an argument. It means it is going to read from the standard input stream of the program. The java.util package should be import while using Scanner class. It also converts the Bytes (from the input stream) into characters using the platform's default charset. 2.5.1 Methods of Java Scanner Class Java Scanner class provides the following methods to read different primitives types: Method Description It is used to scan the next token of the input as an int nextInt() integer. 38 Chapter 2: Java Terminologies float nextFloat() It is used to scan the next token of the input as a float. double It is used to scan the next token of the input as a nextDouble() double. byte nextByte() It is used to scan the next token of the input as a byte. String nextLine() Advances this scanner past the current line. boolean It is used to scan the next token of the input into a nextBoolean() boolean value. long nextLong() It is used to scan the next token of the input as a long. short It is used to scan the next token of the input as a Short. nextShort() BigInteger It is used to scan the next token of the input as a nextBigInteger() BigInteger. BigDecimal It is used to scan the next token of the input as a nextBigDecimal() BigDecimal. The following example allows user to read an integer form the System.in. import java.util.*; class UserInputDemo { public static void main(String[] args) { Scanner sc= new Scanner(System.in); //System.in is a standar d input stream System.out.print("Enter first number- "); int a= sc.nextInt(); System.out.print("Enter second number- "); int b= sc.nextInt(); System.out.print("Enter third number- "); int c= sc.nextInt(); int d=a+b+c; System.out.println("Total= " +d); 39 Chapter 2: Java Terminologies } } Output: An example, in which allow user to read string input. import java.util.*; class UserInputDemo1 { public static void main(String[] args) { Scanner sc= new Scanner(System.in); //System.in is a standard input stream System.out.print("Enter a string: "); String str= sc.nextLine(); //reads string System.out.print("You have entered: "+str); } } Output: 2.5.2 Reading Numbers from the Keyboard You know how to use the nextDouble() method in the Scanner class to read a double value from the keyboard. 40 Chapter 2: Java Terminologies Here are examples for reading values of various types from the keyboard: If you enter a value with an incorrect range or format, a runtime error would occur. For example, you enter a value 128 for line 3, an error would occur because 128 is out of range for a byte type integer. 2.6 Java Identifiers In programming languages, identifiers are used for identification purposes. In Java, an identifier can be a class name, method name, variable name, or label. For 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. 41 Chapter 2: Java Terminologies args : variable name. a : variable name. There are certain rules for defining a valid java identifier. These rules must be followed, otherwise we get compile-time error. The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “joe@” is not a valid java identifier as it contain ‘@’ special character. Identifiers should not start with digits([0-9]). For example “123joe” is a 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 while is a reserved word. There are 53 reserved words in Java. Examples of valid identifiers : MyVariable, MYVARIABLE, myvariable, x, I, x1, i1, _myvariable, $myvariable, sum_of_array, comp123 Examples of invalid identifiers : My Variable //contains a space 123comp //Begins with a digit a+c //plus sign is not an alphanumeric character variable-2 //hyphen is not an alphanumeric character 42 Chapter 2: Java Terminologies sum_&_difference // ampersand is not an alphanumeric character Reserved Words : Any programming language reserves some words to represent functionalities defined by that language. These words are called reserved words.They can be briefly categorized into two parts : keywords(50) and literals(3). Keywords define functionalities and literals define a value. Identifiers are used by symbol tables in various analyzing phases(like lexical, syntax, semantic) of a compiler architecture. A list of Java keywords or reserved words are given below: abstract, Boolean, break, byte, case, catch, char, class, continue, default, do, double, else, enum, extends, final, finally, float, for, if, implements , import, instanceof, int, interface, long, Native, new, null, package, private, protected, public ,return, short, static, strictfp, super, switch, synchronized , this, throw, transient, try, void, while. 2.7 Java operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups :Arithmetic Operators, Relational Operators, Bitwise Operators, Logical Operators, Assignment Operators, Misc Operators 2.7.1 The Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators − 43 Chapter 2: Java Terminologies Operator Description Example Adds values on either side of + (Addition) A + B will give 30 the operator. Subtracts right-hand operand - (Subtraction) A - B will give -10 from left-hand operand. Multiplies values on either * (Multiplication) A * B will give 200 side of the operator. Divides left-hand operand by / (Division) B / A will give 2 right-hand operand. Divides left-hand operand by % (Modulus) right-hand operand and B % A will give 0 returns remainder. Increases the value of ++ (Increment) B++ gives 21 operand by 1. Decreases the value of -- (Decrement) B-- gives 19 operand by 1. 2.7.2 The Relational Operators There are following relational operators supported by Java language. Operator Description Example Checks if the values of two (A == B) is not == (equal to) operands are equal or not, if yes true. then condition becomes true. Checks if the values of two != (not equal operands are equal or not, if (A != B) is true. to) values are not equal then condition becomes true. Checks if the value of left operand is greater than the > (greater than) (A > B) is not true. value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of < (less than) (A < B) is true. right operand, if yes then condition becomes true. >= (greater Checks if the value of left (A >= B) is not than or equal operand is greater than or equal true. to) to the value of right operand, if 44 Chapter 2: Java Terminologies yes then condition becomes true. Checks if the value of left