0% found this document useful (0 votes)
1 views

Java Datatype, Variables, Operators, Keywords, Naming Convention Notes

Java Data type, Variables, Operators, Keywords, Naming convention Notes

Uploaded by

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

Java Datatype, Variables, Operators, Keywords, Naming Convention Notes

Java Data type, Variables, Operators, Keywords, Naming convention Notes

Uploaded by

ashwini bhosale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
6, Data Types (Primitive Data Types) Iyery variable in java tas a data lype. Data types specify the size and type of values that can be tored, Javea langnngo is rich in its datw types, ‘Tho variety of data types available allow the progeammer to select the type appropriate to the needs of the application, There aro two types of data types in java: 1. Primitive/Primary data types: These datn types are also called as Intrinsle or built in data types. Hi, Non-Primitive/Secondary data types: These data types are also called as derived data types. These aro formed using the primitive data types. Derived types also known as reference types. The following figure shows the various types of data types, Data typos In Java Primitive Non-primitive (Intrinsic) (derived) Numorlc Non-numerlc Classes Interface Arrays Integer Real Character Boolean 4 Float Double Data typos In Java 6.1 Primitive (Intrinsic) Data Types 1. Numeric a, Integer type: Integer type can hold whole numbers such as 123,-96 and 5639. Java supports four types of integers such as byte, short, int and long. Integer byte short int long Integer data type F value Java does not support the concept of unsigned type and therefore all java yall signed meaning they can be positive or megalve, short | 2bytes | — 32,768 32,767 int | 4bytes | -2,147,483,648 2,147,483,647 — 9,223,372,036, 854,775,808 Each integer type in java has a corresponding wrapper class: Bye fh Long. Each of these classes defines the MIN_VALUE and MAX’ me b. Real types/floating point iypeds Integer types can hold only whole ni ‘we use another type known as floating point type to hold numbers (decimal point) parts such as 89.60 and -2.896. There are two types of floating point storage in java the following tabled and ranges of this type. Floating point Float Double Table 1.2: Size and range of floating point type pal Size] Mintmum valu | Maximumn VAtU)] Float | 4 bytes 3.4e-038 3.4e + 038 double | 8 bytes 1.7e - 308 1.7e +308 ee The float type values are single-precision numbers while the double | typ double-precision numbers. Floating Point numbers are treated as double-precision quantities. To force them to bein single-precision mode, we must append F or F to the numbers, Example, 1.23F, 8.690854F Double precision types are used when we need greater precision in storage of floating point numbers, All mathematical functio such as type value, a Floating point data type support a special value known as Not-a-Number(NaN). NaN is used to represent the result of operator such as dividing zero by zero, where an actual number is not produced. Most operations that have NAN as an operand will produce NaN as a result. The float and double primitive type have corresponding classes, named Float and Double. Each of these classes defines the following useful constants MIN_VALUE, MAX_VALUE,NEGATIVE_INFINITY, POSITIVE_INFINITY and NaN. 1 Write a program in Java to convert the temperature in Fahrenheit to Celsius using following formula. C=F-32/1.8 Class temp { Public static void main(string args{}) { . 60s, tan, sqrt, pow return double DataInputStream in = new DataInputStream(System. in); float F,C; F-float.parsePloat (System. in); C= (F-32)/1.8; System.out.printin(“Temperature from F° to C*i 1 _ Non-Numeric Types The non-numeric data types are Non-numeric Character Boolean character a, Character: In order to store character constants in memory, Java provides data type called char, The char type assumes a size a 2 bytes but, basically, it can hold only a single character. ill Short Summary about P; 6.2 In addition to the eight primitive data type, java defines two three additional categories of data ty { Classes: Java programs consists of class definitions, each class defines a new data t can be manipulated by java programs. For example, Class Shape int a, b; get_data() { The char type represents the unicodes characters. 7 The character class defines a number of useful static methods for Ae ne character, including is DigitQ, is Lower Case() and foUpper Case 0, ete metho Boolean type: Boolean type is used when we want to test a particular condition y ‘tak the execution of the Program. There are only two values that a Boolean type can true or fai Boolean type is denoted by the keyword boolean and uses only one bit of storage. Boolean values are often used in selection and iteration — stat The words true and false table cannot be used as identifiers. itive Data Type ‘Numeric byte | 1 Bytes (Integer Type) | short__| 2 Bytes int 4 Bytes long | 8 Bytes Floating Type |float__| 4 Bytes double_| 8 Bytes (Non-numeric) Character char | 2 Bytes Boolean boolean | 1 Bit Derived (Reference) Data Types Non-primitive (derived) Va a ee Classes Interface Arrays This makes a shape a new data type in that program, ii, Arrays: An array type represents a li Sooteeic ofsinie deere ts a list of values of some other type. As we know, an array is An array declaration is same as in CH. Example, char name[30) int rolino[20}; ‘We will study arrays in depth in later chapters. Interfaces: inheritance This is the new feature introduced in Java. Java does not support multiple: that is the concept of two base classes and one derived class. Figure 1.18 This feature is accomplished in java through interfaces. 6.3. Java Tokens The smallest individual units in a program are known as fokens. The compiler recognizes it for building up expressions and statements. A java program is basically a collection of classes. A class is defined by a set of declarations, statements and methods containing executable statements. Most statements contain expressions, which describe the actions carried out on data. In simple terms, a java program is a collection of tokens, comments and white spaces. Java language has seven types of tokens. Java tokons [Vantabies][Taontitow Literals} [Constants 6.4 Variables A variable is an identifier that denotes a storage location used to store a data value. ‘The variables value varies through the program execution. In java, every variable has a data type, In order, Example, int a, float x, y; char name; Boolean flag; double salary; Rules for Declaring Variables it They must not begin with a digit. TOTAL. iv. It should not be a key word. Vv. White space is not allowed. Underscores are allowed. Example, char name_x; int a1, a2, a3; Syntax data type variable name; Example, int Roll_no Uppercase and lowercase are distinct, T! Variable names can be of any length, A variable name must begin with a letter, to declare a variable first place the data type followed by the name of the variable. value (true/false); EEE initialization of Variable fet co the value “emue™ 7 Scope of Variables Introduction toy, ‘ov, ava Progr: mMmin Ariable dec, 1y Java, The b; re ‘ves: aration is a statement that T ay io al variables must be declared before they : s sh asic form (syntax) of a variable declaration { datatype vy, The 4 n be used. own here: ‘ariable_name; : whi old and Atatype determines what values it can hi at operations can },, Performed on it, See the following example for variables declaration: sable that can Store value o¢ int num; //represents that num is a variab ‘int type. : it can store string oe that name is a variable thal value. String name; i that can take boolean boolean bol; //represents that bol is a variable —— jable. An initialization is an assignment made when you declare a oe enemas leans, You can assign a value to a variable at the declaration time by operator (=). The assignment operator is the equal sign (=); any value to the right of the equal sign is assigned to the variable on the left of the equal sign. For example : int num = 1000; // this Vine declares num as an) int variable which holds value "1000". boolean bol = true; // This: Vine declares bol as boolean variable which jis Scope refers to the lifetime and accessibility of a variable. The scope of a variable defines the sec tion of the code in. which the’ variable is accessible or visible. ; The lifetime of a variable refers to how long the variable exists before it is destroyed. Fig. 1.27 shows types of variables, Flypes of variabieg] Local variable = Instance variable| Fig. 1.27 1.32 a Java Programming jyetion to Jav8 1, Local Variables: eer * Local variables ai Sacer ecaines canaere in methods, constructors, or blocks. fe local vanauieenS sed for local variables. ia ‘S Visi ad: oe ‘ble only within the declared method, constructor or block. public class Test re void catagec) ‘int age = 0; age = age + 11; System.out. pri, i. ; T-PrintinC"cat age ist " + age): ub ic voi PUPNE static void main¢string argst]) Test test = new test(); test.catage(); } . ' 3 Output: Cat age is: 11 2, Class/static Variables: + Variables declared inside the class with static keyword are called as static variables. + Class variables also known as static variables are declared with the static keyword ina class, but outside a method, constructor or a block. * Static variables can be accessed with following three ways: (a) with class name. (b) with reference variable which contains null. (©) with reference variable which contains object. * Static variables can be accessed by calling with the class name like, Classname.variableName. Example: import java.io.*; public class Employee { // salary variable is a private static variable private static double salary // DEPARTMENT is a constant public static final String DEPARTMENT = “Production”; public static void main(string args(]){ salary = 800 . system. out .printIn(DEPARTMENT+"average salary:" +salary); } 3 Output: production average salary: 8000 1.33 a Introduction. , x 23a Prog a —SRaramming . ‘9 8. called a: Instance Vatiabtes: tle eyword is Ae * Varia at stil STALE dey ansi ss withou will be allog, variables Aeclared inside the class Y jects hac memory Mocatey * Instance vari ce or objec created. ins Obj thas ttiables belongs to instance OF jcc js crel ich CONTAINS Objecr 2 JOE Mat instance variables tnen abject arable ence variables can access with the Pe" otic variabl iit be allocated for i BStance variables can also be called as NOW wi he tv . Ss For multiple object creation, multiple time instance variables. Example: AMPOrt java.io.*; Public class Employee i S. { ee apte for any child are 77 this instance variable is visible sae public string name: an employee class OnlY: // salary variable is visible in En? Private double salary; $ 7/ The name variable is assigned in the cae Employee (String empName) constructor» i name = empName; 7/ The salary variable is assigned a value: peli void SetSalary(double empSal) salary = empSal; // This method prints the employee details. public void printemp({ System.out.printin("name: " + name); System.out.printin("salary:" + salary); yi public static void main(String args(]) ig { # Employee empOne = new Employee(“Amar"); empone. setSalary(10000) ; empone.printemp(); + Output: name: Amar salary:10000.0 Constants Constant program. A constant in Java is used to map an exact and unchan; Constants are used in programming to make code readable. - Constant in Java can be declared by using the keyword final, tant cannot change throughout the program. . mewalue of a constal 1.34 a Java refer to fixed values that do not change during the execution of ti | ging value to a variable name a bit more robust and human ally wants to q, Tgener ni EB} oerarors rrpreeearns * The task of computation 1s known as operate” fic operations USIRg the . : ‘©Me operations in a program. some spect * Operators. are special symbols that perform nds. AN operator js , Operands and operator. re called oped * The data items that the operators act ee to be performes” symbi ke ifies an opera ymbol or a keyword that specifies an PEF rs, * Fig. 1.28 shows the concept of operands and Pe rans + Ifan operator acts on a single variable, two variables, it is called binary operator, zex+Y operator " i operator o; Fig. 1.28 operator, if an tor on it is cle at acts on three variables, and i then it is called ternary operator. Types of Operators 1. Arithmetic Operators : * Arithmetic operators are used in mat thematical expressions in the same way that they are used in algebra. ieelt i i ns like additi + Arithmetic operators are used to perform some mathematical ope ae ects subtraction, multiplication, division, and modulo (or remainder). y performed on an expression or operands. * According to number of operands required Unary (one operand), binary (two operands) an for an operator, they are classified as d ternary (three operands) operators. © The following table lists the arithmetic operators. Assume integer variable A holds 10 Operat and variable B holds 20, then: + (Addition) ‘Adds values on either side of the operator. - (Subtraction) | Subtracts right hand operand from left hand operand. | A- B =-10 * Multiplies values on either side of the operator A*B=200 (Multiplication) / Division) Divides left hand operand by right hand operand, BrAs2 | % (Modulus) Divides left hand operand by right hand Operand and | B% A=0 returns remainder, ++ Increment Increases the value of operand by 1 Bee gives 21 1 i Decrement Decreases the values of operand by 1 £ | B-- gives 19 136 programming Introduction to Relational Operators When we want to compare vai operators are used. After compa: program. Relational operators can be called as compariso: ava supports six different relational operators ee Jv. lues i nae Of two variables for various means, relational 6 these values we may take several decisions in the Foperator Meai y Sra alee Op —_™ ning Explanation Example | Result _| qt operator This operator is used | 10==10 True for check equality. Not equal to operator | ‘This operator is used | 101=10 False for check Inequality. > Greater than operator | This operator is used | 10>10 False for check greater value. < Less than operator This operator is used | 10<10 False for check lesser value. >= Greater than or equal | This operator is used | 10>=10 True to operator for check greater as well as equality. <= | Less than or equal to | This operator is used | 10<=10 True operator for check lesser as well as equality. 3. Conditional Operators : When we want to form compound conditions by combining two or more relations, then we can use logical operators. Logical operators, compare or evaluate logical and relational expressions. There are only three logical operators which are related with the logical decisions. ‘Assume Boolean variables A holds true and variable B holds false, then: Operator: Ga Description: If both the operands are non-zero, then the condition becomes true. If any of the two operands are non- zero, then the condition becomes true. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. && (Logical AND operator) (A && B) is false. || (Logical OR Operator) (A || B) is true. ! (Logical NOT Operator) (A && B) is true. 1.37 ramming Bitw; itwise Operators : I order to Java, ifting These operators are used for testing the bits as Well 9 shi hese can be applied to integer types only: eee operator works on bits (0 or 1) and i 0; and y = 13; Now in binary format they will be & X= 0011 1100 y = 0000 1101 x&y = 0000 1100 Xly = 0011 1101 xAy = 0011 0001 ~x= 1100 0011 variable B holds 13 then: Manipulate the data at the bit level perform The following table lists the bitwise operators. Assume integer the pitwise op’ pit by bito lows: erators are provided jn them to left or right ete. peration. Assume if x = variable A holds 60 and of bits specified by the right operand and shifted values are filled up with zeros, Tape 7] = Ss ———— <= Example =; Operator.= = = Description: a sz —— 7 if | (A & B) will give 12 which is” & (Binary AND Operator) _ | It copies a bit to the result i we it exists in both operands. _| 0000 1100 __ aman | Binary OR Operator) Tt copies a bit if it exists in | (A | B) will give 61 which is either operand. 0011 1101 2 —_ 4 (Binary XOR Operator) It copies the bit if it is set in | (A * B) will give 49 which is | one operand but not both. _| 0011 0001 | ~ (Binary Ones This is unary and has the | (~A ) will give -61 which is | Complement Operator) effect of ‘flipping’ bits. 1100. 0011 in 2's | complement form due to a | . signed binary number. << (Binary Left Shift The left operands value is | A << 2 will give 240 which Operator) moved left by the number | is 1111 0000 of bits specified by the right operand. >> (Binary Right Shift The left operands value is | A >> 2 will give 15 which is Operator) moved right by the number | 1111 of bits specified by the right | operand. | >>> (Shift right zero fill The left operands value is | A>>>2 will ai ich is | operator) moved right by the number Brel) which ts 0000 1111 1.38 — - ava 09 conditional Operator (?:) : Conditional operator is also known { gnis operator consists of three oper, 5. the goal of the operator is to deciai { gyntax: variable x = Cexpressio « ample: Following program checks qaass PosNeg duction to Javs as ternary operator, Rate ua sed to evaluate Boolean expressions. OF vetee ue should be assigned to the variable. whether nan bee wee value 4f false T is positive or negative. { . public static void main(string args[}) { int a=10; int fla if (flag system.out.printIn("Number is positive"); else system.out.printIn("Number is negative"); ‘output: number is positive 6, Instanceof Operator : +. The instanceof operator compares an object to a specified type. The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). The instanceof operator is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that have null value, it returns false. «Syntax: (object reference variable) instanceof (class/interface type) If the object referred by the variable on the left side of the operator passes the IS-A | check for the class/intetface type on the right side, then the result will be true. Example: public class Test { public static void main(string args[]) { . String name = "James"; 7/ following will return true since name is type of String name instanceof string; boolean result System.out.printIn( result )j Output: true ‘ 1.39 alee ails ‘Java constants 1 Numeric constant Character constant Integor Real? Character Sting constant constant constant constant Java Constants i. Integer constant: An integer constant refers to a sequence of digits. There are three types of integers namely, decimal integer, octal integer and hexadecimal integer. Real constant: Integer numbers are inadequate to Tepresent quantities that vary continuously such as distance, heights, temperature, ctc. These quantities are represented by numbers containing fractional parts like 17.548. Such number are called real (or floats point) constants. A floating point constant comprises of four parts a. awhole number b. adecimal point cc, ~a fractional part = a. anexporient iii, Character constant: A single character constant contains a single character enclosed with a pair of single quotes marks. Sx yp String constant: A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabet, digits, special characters and blank space: Example,: “Hello World” “2012” “9/3” 6.11 Keywords Keywords are also known as Reserved words, whose meaning is already being defined into java libraries. Keywords cannot be used as variable names, as they have special meaning into the java class libraries. Java language has 50 keywords, These keywords, combined with operators and separates according to the syntax, form definition of the java language. BM keywords are to be written in /ower-case letters, ‘Java constants Numeric constant ‘Character constant Integor Real? Character Siting constant constant onetant constant Java Constants Integer constant: An integer constant refers to a sequence of digits. There are three types of integers namely, decimal integer, octal integer and hexadecimal integer. Real constant: Integer numbers are inadequate to represent quantities that vary continuously such as distance, heights, temperature, etc. These quantities are represented by numbers containing fractional parts like 17.548. Such number are called real (or floats point) constants. ‘A floating point constant comprises of four parts a. a whole number b. adecimal point c. ~a fractional part d. anexporient Character constant: A single character constant contains a single character enclosed with 2 pair of single quotes marks. SAX? iv. String constant: A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabet, digits, special characters and blank space. “2012” “9/3” 6.11 Keywords Keywords are also known as Reserved words, whose meaning is already being defined into java libraries. Keyan cannot be used as variable names, as they have special meaning into the java class jibraries. Java language has 50 keywords. These keywords, combined with operators and separates according ome form definition of the java language. All keywords are to be written in /ower-case ers, al > , ; sansa ——(@)————* I Toble 1.3: Java Keywords abstract | final ‘pubic | | byte | goto “[ stcictp class _| instance of _| this 4 do native fy oxtends | protected _| break tor Static char import_| synchronized | default tong _| transient ‘enum Private _| while float short | boolean Implements switch | catch extends throws _| continue interface volatile | else package assert _| finally return case__| of super const | int throw double_| new void ot 6.12 Separators Separators are symbols used to indicate where groups of code are divided and arranged. 1 basically define the shape and function of our code. Following are the lists of java separators: Paranthesis(): It is used to enclose parameters in method definition and invocation, also for defining precedence in expressions, containing expressions for flow control surrounding cast types. Braces{}: Used to contain the values of automatically ini of code for classes, methods and local scopes. Brackets[]: Used to declare array types and for dereferencing array values. Semicolon (;): Used to separate statement. Comma(,): Used to separate consecutive identifiers in a variable declaratio chain statements together inside a * for statement. Period (.): Used to separate package names from sub-packages and classes, a separate a variable or method from a reference variable, 5.8 Naming Conventions Names of all public methods and instance variables start with a leading lowercase letter, Example, salary calculate sum percentage i, When more than one words are used in a name, the second and subsequent words are marked with a leading uppercase letter, Example, dayofMonths totalmarks basicSalary getData calculateData All private and local variables use only lowercase letter combined with underscores. Example, length roll_no basic_salary 6.9 All classes nd interfrees starts, Example, With a leading upperense letter Student Rectangle MeActCircle between . iderscares Variables that represent constant values usoe all Uupperense letter and und words, Example, Pl MAX_VALUE TOTAL LENGTH ‘Note: All these are conventions and not rules, Literals

You might also like