Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Java Notes 2

Java pdf notes

Uploaded by

aloklkr570
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Notes 2

Java pdf notes

Uploaded by

aloklkr570
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
22 Programming in Java 2.7 PROGRAM STRUCTUR' ‘A Java application con! defined as an instance o and methods) specified operations on the fields an Figure 2.7). Ses 1ST fa collectio s. A class is asemeats i Object sists of aC Z pject) contains the members ce (obj (fie fhe class. Each instance 7 aa value. A method ag in the class. A fi ents to th tn oe vues that ae passed. 86 STE © Method (so, E pena n of classe’ Instruction Local variables Instruction Local variables Class and Instance variables Figure 2.7. Program structure Let us now create our first Java program. Example 2.1 below shows a very simple ‘Java program which displays a string on the console. It has just-one print statement (The program is explained in Section 2.7.3). BSR RS SARE TT Example 2.1 First Java Program PuiXy 7 Cal] this file “Example. java” */ L2k/ Class Example { Puss) //your program starts execut: ‘jon with a /*\4*/ public static void main (String args[ ae oe /US*/——System.out.printIn(“This i fat 8 This is a simple Java program”): Puree. 2.7.1 How to Execute a Java Program There i are three easy steps for Successfully executing a J Y g a Java program: 1, Entering the source code The above program (Example 2.1) can be written in any text editor (like Notepad) but make sure it is written exactly the same way it is shown. 2. Saving the source code Now that you’ve written the code in Notepad, this is how you'll save it © Select File | Save As from the notepad menu. ¢ Inthe ‘File name’ field, type “Example. java” within double quotes Inthe ‘Save as type’ field select All Files Cs), © Click enter to save the file 3. Compiling and running the source Java programs are compiled using DOS. For opening DOS, type cmd at the run prompt and move to the folder that contains the saved Example. java file. Now compile the program using javac, specifying the name of the source file on the command line as shown below. (assuming the file was saved in a folder javaeg in the C drive.) C:\> cd javaeg // change to directory javaeg using cd command C:\javaeg\>javac Example. java The javac compiler creates a file called Example.class (in the same directory). This class contains the bytecode version of the program. This bytecode will be executed by the Java interpreter using java followed by the class name as shown below. C:\javaeg\>java Example The output of the program is shown below: This is a simple Java program VARIABLES icntiaesisinaraiamene name rSiersoneespouiae TGA SRA Variable is a symbolic name to refer to a memory location used to store values that can change during the execution of a program. Java declares its variables in the following manner: int noOfWatts == 100; // variable declaration Data type Identifier Literal A variable declaration involves specifying the type (data type), name (identifier), and value (literal) according to the type of the variable. Let us have a look at the three components in detail. 3.2 PRIMITIVE DATA TYPES Primitive types are the basic building blocks of any programming language. A pr; ‘i ies Mitive data type can have only one value at a time and is the simplest built-in form Of dag within Java. All variables in Java have to be declared before they can be used, Which is why Java is termed as a strongly typed language. There are eight primitive type, 7 Java, as follows: byte short |-—> For Whole Number int long float | For Real Numbers double —__J char» Characters boolean———» Boolean Java is portable across com, puter platforms. C and C+ leave the size of data types to the machine and the compiler. , but Java specifies everything. “© Allinteger (byte, short, int, long) and floating-point types (float, double) are signed in Java. byte: It is a 1-byte (8-bit) signed 2” to 127 (inclusive). The byte savings actually matter. $ complement integer. It ranges from -128 data type can be used where the memory short: It is a 2-byte (16-bit) signed 2’s complement integer. It ranges from —32,768 to 32,767 (inclusive). As with byte, you can use a short to save memory. int: It is a 4-byte (32-bit) signed 2’s complement integer. It ranges from ~2,147,483,648 to 2,147,483,64 data type is the default choice, long: It is an 8-byte (64-bit) si ~9,223,372,036,854,775 This data type should b wider than int. 7 (inclusive). For integral values, this igned 2’s complement integer. It ranges from 808 to 9,223,372,036,854,775,807 (inclusive). e used only when you need a range of values Floating point conforms to the IEEE 754-1985 binary floating point standard. float: It is a single-precision 32-bit f1 joating point. It ranges from 1.4012984643248 1 7e-45f to 3.40282 '3476638528860e+38f. Java Programming Constructs 49 double: This data type is a double-precision 64-bit floating point. It ranges from 4,94065645841246544e-324 to 1.79769313486231570e+308. For decimal numbers, this data type is the default choice. boolean: Ithas only two possible values: true and false. The size of this data type is not precisely defined, char: The unsigned char data type is a single 16-bit Unicode character. It ranges from *\u0000° (or 0) to ‘\uffff’ (or 65,535 inclusive). "Unlike C/C++, where handling of character sequences is tedious, Java provides a class named “String” for handling character strings enclosed within double quotes. Although, not a primitive data type, Java String solves much of the complexity with ease. 3.3 IDENTIFIER sostsatianiesnsnnatssasnennmuene teria eae amen Identifiers are names assigned to variables, constants, methods, classes, packages, and interfaces. No limit has been specified for the length of a variable name. Identifiers can have letters, numbers, underscores, and any currency symbol. However they may only begin with a letter, underscore, or a dollar sign. Digits cannot be the first character in an identifier. 3.3.1 Rules for Naming . The first character of an identifier must be a /etter, an underscore, or a dollar sign (8). Use /etter, underscore, dollar sign, or digit for subsequent characters. Note that white spaces are not allowed within identifiers. v . Identifiers are case-sensitive. This means that Total Price and total_price are different identifiers. 4, Do not use Java’s reserved keywords. A few examples of legal and illegal identifiers are shown below. MyClass Wy Class amount 23amount, _totalPay -totalpay total_Connission total@conmission 50 Programming in Java 3.3.2 Naming Convention Names should be kept according 10 as shown in Fig. 3.1. their usage, as it is meaningful and easy to remembe, eae > ___ > | Package Declaration — hello 3 ase claetence ies ie Sd Importing Other Packages Cee ee public class Hel loworld Class Declaration Beginning of the class { public static void main(argsC]) Main method declaration System. out .printin(“Hel lo How are You?” ); Print statement —— pS yet Aad se ose eel tle a sealer End of main method } End of the class Figure 3.1 Naming convention used in Java Class or Interface identifiers begin with a capital letter. The first alphabet of every internal word is capitalized. All other letters are in lowercase. public class MyClass // class identifier: MyClass ‘interface Calculator; // interface identifier: Calculator Variable or Method identifiers start with a lowercase letter. The first alphabet of every Internal word is capitalized. All other letters are in lowercase. ‘int totalPay: // variable identifier: totalPay MyClass.showResult(); // MyClass is the Class Name and showResult() is a method of // MyClass Constant identifiers are specified in upper case. Underscores are used to separate internal words. Final double TAX RATE =0.05: // constant identi fier: TAX_RATE Package identifiers consist of all lowercase letters. package mypackage.. subpackage.. subpackage; //Package Declaration Java Programming Constructs 51 3.3.3 Keywords Keywords are predefined identifiers meant for a specific purpose and cannot be used for identifying used defined classes, variables, methods, packages and interfaces. All keywords are in lowercase. Table 3.1 lists the keywords in Java. Table 3.1. Keywords in Java abstract 7 [assert 7 boolean break byte case catch char class continue | defautt 7 do double else [enum [extends ¢ final finally float [for lif implements, | import instanceof int | interface tong native new package private protected public return short static strictfp, _| super switch synchronized | this throw ‘throws transient ty void volatile ~ [while Table 3.2 lists the reserved keywords in Java. S Table 3.2 Reserved keywords const goto 3.4 LITERALS iccemetenemenrnertacener erica ME DE ET COON A literal is a value that can be passed to a variable constant in a program. Literals can be numeric (integer, float, long, etc), boolean, character or string values. Integer literals can be decimal, octal, or hexadecimal. In case octal literals have to be specified, the value must be prefixed with a zero and only digits from 0 to 7 are allowed. For example, int x=011; //value inx is9 Hexadecimal literals are prefixed with Ox or oX; the digits 0 through 9 and a through ‘flor A through F) are only allowed. For example, int y= 0x0001; | //value iny is 1 All integer literals are of type int, by default, To define them as long, we can place a suffix of L or / afier the number for instance: Tong 1 = 23456789981 Table 3.5 Data Types: Size, Default Value and Range byte 0 8 =128 to 127 (inclusive) short 0 16 ~32,768 to 32,767 (inclusive) int 0 32 ~2,147,483,648 to 2,147,483,647 (inclusive) long OL 64 ~9,223,372,036,854,775,808 to 9,223,372,03 6,854,775,807 (inclusive). float 0.0F 32 1.401298464324817e-45f to 3.402823476638 528860e+38f. double 0.00 64 4.94065645841246544e-324 to 1.797693134 86231570e+308. char “\u0000" 16 0 to 65535 boolean —_| false Not true or false defined Table 3.6 lists the reserved literals in Java. Table 3.6 Reserved Literals tue | _ false null 3.5 OPERATORS simerecciesicissntstaee aU SNA NS ARTE An operator performs an action on one or two operands. An operator that performs an action on one operand is called a unary operator (+,-, ++, ——). An operator that performs an action on two operands is called a binary operator. An operator that performs an action on three operands is called a fernary operator (?:). Java provides support for all the three operators, Let us begin the discussion with binary operators first.

You might also like