0% found this document useful (0 votes)
9 views26 pages

Chapter 2 Values and Data Types

This document provides an overview of values and data types in Java, covering literals, identifiers, variables, and naming conventions. It explains the different types of variables (local, instance, static) and data types (primitive and non-primitive), along with their characteristics and examples. Additionally, it discusses the final keyword, escape sequences, and type conversion methods in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
9 views26 pages

Chapter 2 Values and Data Types

This document provides an overview of values and data types in Java, covering literals, identifiers, variables, and naming conventions. It explains the different types of variables (local, instance, static) and data types (primitive and non-primitive), along with their characteristics and examples. Additionally, it discusses the final keyword, escape sequences, and type conversion methods in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Parv Poddar Java Notes V 1.0 Computer Applications Chapter 2 Chapter 2 % alues and Data Types | N COACHING CENTER Inthis Chapter Literals © Identifier (0 Naming Conventions Variables © What is Variable © Howto Use Variable © How tostore in Variable © How to choose a variable name © Naming conventions © Data Types ‘+ What is Data Types © How many Data Types are there © How toselect a appropriate data type 0. How togive data type to a variable © Final Keyword * Escape Sequence ( Part of Literals ) + Type Conversion © How to Convert of One Data Type to: Literals : Aconstant value can be assigned t pean a.” Character b. Escape Sequence *** 4, String Literal 5. Boolean Literal 6. Null Literal > null or \O PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR Identifiers ‘An identifier is a name we give to entities like variables, methods, classes, etc, We will learn about all these entities in later chapters. For now, just remember that whenever we define an entity, we assign it anname which is called an identifier. AllJava variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y] or more descriptive names (age, sum, totalVolume). Note: It is recommended to use descriptive names in order to create understandable and maintainable codé= Rules for writing Identifiers ‘Identifiers can be a combination of lowercase (a z) and uppercase (A -Z) letters, digits (0 - 9), dollar sign ($) or an underscore (_). Special characters (*, % #,!, @, etc.) cannot be present in identifiers. €g, Message1, num_max are valid identifiers and num@ is an invalid identifier. ‘Identifiers cannot start with a digit. €g, 2num isan invalid identifier # InJava, identifier names are case-sensitive, ie. num and Num will be treated as different. «Keywords cannot be used as identifiers (Keywords are explained in the previous chapter) « £g, class isan invalid identifier because it isa keyword. Naming Conventions Pascal -> First Letter in Capital Case > used for class names. Camel -> First Letter in Small Case -> used for Methods nates Good Practices to Name Identifiers ‘There are some good practices to,name identifiers which should be followed but are not mandatory. ‘+ Identifiers should beskept meaningful so that understanding code is easier. Thereforejinstead of using names like x, y, a,b, etc. for identifiers, use somémeaningful names. For example, ifwe are stofiig the product ofttwo numbers in a variable, then the name\of tNatyariable should be kept as product. ‘+ Namesoof variables afd methods should contain only Jowercase letters. For example, name, display(), etc +” Clais names should start with capital letters. For example, PersonyStudent, Books, etc ‘+ Ifyou wanihto name a variable with multiple words, then name it as multiple words separated by underscores. For example, first name, last name, etc. ‘+ Ifyou want to name a method with multiple words, then name it in CamelCase format. For example, getNamet }, printMessaget ), etc + If you want to name 2 class with multiple words, then name it in Pascal Case format. For example, StudentRecord, BookAuthor, etc 3 PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR. Java Variables Till now, we know how to print anything on screen Resened Ara Now, let's learn about variables in lava which are somewhat similar to the variable we use in Mathematics. eet ‘Avariable is a container which holds the value while the Java program is executed. Avariable is assigned with a data type. ‘Avariable isthe name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination Fa ‘of "vary + able" which means its value can be changed. Variables are containers for storing data values. - >A variable is used to store some value. You can think of a variable as a storage which has ‘a name and stores some value. (Class 10) -> Function Chapter ‘There are three types of variables in java: local, instance and st ‘Types of Variables ‘There are three types of variables in Java: © local variable © instance variable ‘© static variable 1) Local Variable ‘Avvariable declared inside the body of tl called local variable. You can use this variable only within n't even aware that the variable exists. happens only once when the class is loaded in the memory. PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR 4 Data Types in Java Data types specify the different sizes and values that can be stored in the variable. Data types are defined as the data storage format that’s variable can store to perform a specific operation in 2 fava program, Note: With the help of Data type we can inform the compiler regarding the type of data values that will be stored ina particular variable, (Data types are very much essential to identify the type of value that we can store in an operand.) ‘There are two types of data types in Java / Data types are divided into two groups: Primitive data types ( Fundamental / Basic / Pre-defined / intrinsic / Built-in / Primary } ‘The primitive data types include boolean, char, byte, short, int, long, float and double. Definitions of these data types are available in the java library classes,(called Wrappef Classes) These are independent of any date type and provided by developers of Java software. In Java language, primitive data types are the building blocks of data manipulations ‘These are the most basic data types avellable in Java language. ‘Wrapper classes: ‘A Wrapper class is special kind of class which wraps the value of’ primitive. data type in an object. In [Link] package Java provides a separate class for each of the primitive data typesvnamely Byte, Short, Integer, Long, Float, Double, Character & Boolean. ‘The Wrapper classes contain 2 number of unique methéds for handling primitive data types and objects. Non-primitive data types ( Derived / Pre-defined / See@nday / Reference / Composite ) ‘The non-primitive data types include Classeg, Interfaces, andyarrays. ‘These data types are derived from Primitive deta types or defined by the programmer. Composite data types are directly orindirectly dependent on Primitive data types. Java isa statically-typed programming language, It means, all variables must be detlared before its tse. That is why we need to detlare variable's type and name. ‘There are 8 typas of primitive data types: Slno Data Type Default Value Default size Wrapper Class__Type 1 boolean false 1bit Boolean Stores True or False 2. chat \\wooo0" 2bytes Character ‘Stores Character Literals 3. byte 0 1 byte Byte 4 short o 2 bytes short $n a aa a Stores Integers Numbers 6 long oO jor 8 bytes Long 7 float 0.0f || 0.0F 4 bytes Float @ double 0.04 10.00 B bytes Double Stores Decimals / Reals Numbers 5 PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR Boolean Data Type ‘The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions, ‘The Boolean data type specifies one bit of information, but its "size" can't be defined precisely Example: Boolean one = false Byte Data Type ‘The byte data type is an exemple of primitive data type. It isan 8-bit signed two's complement integer. Its vvalue-range lies between -128 to 127 (inclusive. ts minimum value is -128 and maximum value is 127, ts default value is 0. ‘The byte data type is used to save memory in large arrays where the memory savings is mostrequired. it saves space because a byte is 4 times smaller than an integer. It can also be used in pla¢® of "int" data type. Example: byte a= 10, byte b 20 Short Data Type ‘The short data type is a 16-bit signed two's complement integer, Its walue-rangellies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximumalue is 32)267. Its default value is 0. ‘The short data type can also be used to save memory justlike byte data type. l\short data type is 2 times smaller than an integer. Example: short s = 10000, short r = -5000 Int Data Type ‘The int data type is a 32-bit [Link]'s complement integer. its value-range lies between ~ 2,147,483,648 (-2931) to 2,147, 483,647 (2831 -1) (inclusive), Its minimum value is - 2,147,483,648and ‘maximum value is 2,147,483,647. ts default valle is 0. The int data type is generallypused as a default data type for integral values unless if there is no problem about memory. Example; int a = 109000, int b\= -200000) Long Data Type ‘The long dats type is a 64-bit two's complement integer. Its value-range lies between - 9,223,372,086,854, 775 808(-2"63) to 9,223,372,036, 854,775,807(2°63 -1){inclusive). Its minimum value is -9,223,372,086,854,775,808and maximum value is 9,223,372,036 854,775,807. its default value is 0 ‘The long data type is used when you need a range of values more than those provided by int. Example: long a = 1000001, long b = -200000L PAATHSHALA INSTITUTE —JAVA COURSE ~ PARV PODDAR Float Data Type The float data type is a single-precision 32-bit IEEE 754 floating point Its value range is unlimited. Itis recommended to use afloat (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never be used for precise values, such as currency, Its default value is 0.0F. Example: float fl = 234.5F Double Data Type ‘The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimitedThe double data type is generally used for decimal values just like float. ‘The double data type also should never be used for precise values, such as currency. Its defaultyalue is 0.04. Example: double di = 12.3 Char Data Type ‘The char data type is a single 16-bit Unicode character. Its value-range lies Between "\u0000" (or 0) to "\uffff (or 65,535 inclusive).The char data type is used to store characters, Example: char letterA = 'A’ String string isa term that refers to a set of characters enelésed within doubleGuotes Java provides a class String in java lang package whose objéct can be treated as variable of type String. ‘Why char uses 2 byte in java and what is \u0000 ? Its because java uses Unicode systémnot ASCIl\code system. The \u0000 is the lowest range of Unicode system. Unicode System Unicode is a universal interfationalstandard character encoding that is capable of representing most of the world's written languages. ‘Why java uses Unicode Sistem? Before Unicode, thete were maliy language standards: ASCII American Standatd Code for Information Interchange) for the United States. 180 8858¢i{for Western European Language. KOL-8 for Russian, 6818030 and BIG-S for chinese, and so on. This caused two problems: ‘+ Aparticular code value corresponds to different letters in the various language standards. ‘+ The encodings for languages with large character sets have variable [Link] common characters are encoded as single bytes, other require two or more byte. 7 PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR Solution To solve these problems, a new language standard was developed i.e. Unicode System Inunicode, character holds 2 byte, so java also uses 2 byte for characters lowest value‘\u0000 highest value:\UFFFE For processing java characters are internally represented/defined by their numeric values, (called ASCII code}(American Standard Code for Information Interchange). \Very Important ASCII codes: How to use Variable : 1. Declaration -> int a; 2. Assignment > a=10; 3. Initialization -> int a 0; final Keyword -> Ask sir for detailed explanation.... Symbolic Constant (fil) Definition: The final keyword converts the variable into constaft whose valle cannéthbe’changed at any stage in the program ‘We often need sometimes that the value of a variables) should not thange at any cost. So to implement, this process the final keyword is used, ‘The following format and examples describes the use of final Keyword: Syntax + final datatype variable name = actlalyale; Escape Sequence :- JavalSupports some Special Backslash Character Constants also known as Escape Sequence or Non-Graphic Characters 1. \n-> New Line 4.\’ &\" >for Single & Double Quotation 2. \t-> Horizontal Tab 5.\0-> Null 3. \b *Batk Space Type Casting Suppose weare writing a program and we have an integer variable having a value 10 (an integer) and at some point oftine we want it to be a string ie., “0”. Or a more practical case would be to convert a double (10.2) to an integer (10). We can easily do so in Java using type casting, ‘Type Casting is the conversion of a value from one data type to another data type. For example, we can convert a double value to an int value or a char value to an int value. ‘Type Conversions are of two types - implicit and explicit. PAATHSHALA INSTITUTE —JAVA COURSE ~ PARV PODDAR Implicit Conversion ( Coercion / Type promotion ) Suppose we are adding two numbers, The first number is of type int and the second number is of type double. We cannot add an int and a double because both the numbers have to be of the same data type i.e. either both are int or both are double. Since double is a larger data type than int, therefore while adding, the int variable automatically gets converted into double and then both the double variables add up. Order of size of data types: double > float > long > int > char > short From the above order, we can see that double is the largest data type and short is the smallest data type. Any smaller data type gets implicitly converted into a larger data type when performing arithmetic operations or in any such other expression. For example, when adding a value of type int and a value of type long, the value of type int gets ‘automatically converted to long and then both the values get added. Similarly, a char variable gets converted into an int while performing some arithmetic opération. class Test { public static void main(Stringl] args), { intn=10; char ch =" int sum=n-+ ch; [Link](sum } } Output 14 In the above program, when the variablesiiand ch are added, the integer value (ASCII value) of ch ie. 1104 is added to the value of aitoyproduce a sunv'@F14. Note that every character has an ASCII value. You can get the ASCII chart fr6m here Explicit Conversion ( User defined casting Type narrowing ) We know that a Smaller data type €an be implicitly converted to a larger data type. But what if we want to convert a largendataltype to a smaller data type? Weeéin also Gonvert Ualues from one data type to another as shown below: sgntaity (data-tyney expression; For example, a double value 10.5 can be converted to int as shown below. (int)10.5;, From (Data Type ) To (Data Type ) short int, long, float, double int Jong, float, double Jong float, double 9 PAATHSHALA INSTITUTE — JAVA COURSE — PARV PODDAR byte’ short, int, long, float, double float double char int, long, float, double Class—9 Chapter 3 Values and Data Types Multiple Choice Questions Question 1 A constant which gives the exact representation of data is called 1. Variable 3. Identifier 2. Literal V 4. Chatacter Question 2 A word used in a high level language which has a spegiél meaning @tachedltyft is called 1. Class 3 Keyword ¥ 2. Identifier 4. Whiteral Question 3 A character literal is assigned to a: 1. Char variable ¥ 3y/ String variable 2. Char type literal 4. String literal Question 4 A character literal is enclosed\in: aN CONG [Link] 4th Question 5 A set of charadters iSassigned to: 1, String variable ¥ 3. Boolean variable 2. Static vatinble 4, None n.6 The ASGII codes of upper case alphabets range from 1.965-90V 3, 65-91 2. 60-85 4, 97-122 ion 7 Which of the following results in integer type? 11.4F/3.2D 3 BBV 13.8F/4.6F; 4. none ion 8 Which of the following is non-primitive data? PAATHSHALA INSTITUTE —JAVA COURSE ~ PARV PODDAR 10 1. char 3. object ¥ 2. long 4. short Question 9 Which of the following type is an exact representation of fractional values? 1. char 3. byte 2. double ¥ 4. String Question 10 Boolean Data is used to test a pat representation?” 1. boolean m=true ¥ 3. boolean m="true" 2. boolean m~'true’ 4. none ular condition i.e. true or false. Which of the followinglig’a cOeGE Fill in the blanks Question 1 The character sets of Java is like alphabets of English latiguage Question 2 A standard encoding system way of representing characteris Unicode, Question 3 ASCH code is decimal number to represent character. Question 4 Each individual component of a Jaya statement is)known as token. Question 5 In Java, the constants are also called literals. Question 6 Assignment operatocis used 10 store a value in the variable. Question 7 The comma, exclamation, question mark etc., are termed as Tokens in Java language. Question 8 An clement 6f,Java program that is used to identify a class, function or value is called as identifier. Question 9. Inter type value Socupies 4 bytes in the memory. QuestioiA A Javaexpression that contains all the elements of same data type is pure expression. Write ShoxtAnswers Question 1 What do you mean by data type? Data types are used to identify the type of data a memory location can hold and the associated operations of handling it, Question 2 Define variable with an example. a PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR A variable represents a memory location through a symbolic name which holds a known or unknown value of a particular data type. This name of the variable is used in the program to refer to the stored value. Example: int mathScore = 95; Question 3 What do you mean by constant? Explain with an example. The keyword final before a variable declaration makes it a constant. Its value can't be changed in the pfO wean. Example: final int DAYS_IN_A_WEEK Question 4 State two kinds of data types. Two kinds of data types are: 1. Primitive Datatypes. 2. Non-Primitive Datatypes. Question § What do you understand by Token? Name différent typeof toRens. A token is the smallest clement of a program that is meaningful to the eompiler. The different types of tokens in Java are: 1. Identifiers Ay Separators 2. Literals 5.) Keywords 3. Operators Question 6 What are the rules to assign @ yariable in #Uayaprogramming? 1, Name of the variable should be sequence of alphabets, digits, underscore and dollar sign characters only, 2. It should not start with a digit. 3. It should not be @ keyword or a boolean or null literal Question 7 Explain thettnm ‘type casting"? The process of convértin@one predefined type into another is called type casting, Question 8 PUFform the follwing: (a) [Link] valle of pie (33142) to a variable with the requisite data type. double pi = 142; (b) Assignithe value of (1.732) to a variable with the requisite data type. double x 7325 Question 9 Distinguish between: (a) Integer and floating constant PAATHSHALA INSTITUTE —JAVA COURSE ~ PARV PODDAR 12 Terry Integer Constants represent whole number values like Floating Constants represent fractional numbers like 2, -16, 18246, 24041973, etc, 3.14159, -14.08, 42.0, 675.238, ete. Integer Constants are assigned to variables of data type Floating Constants are assigned to variables of data type —byte, short, int, long, char — float, double (b) Token and Identifier Token emer A token is the smallest clement ofa program that is Identifiers are used to name things like classes, objects, meaningfal to the compiler. variables, arrays, functions an so on. ‘Tokens in Java are categorised into 5 types — Identifier is a typeof token in Java. Keywords, Identifiers, Literals, Punctuators, Operators, (©) Character and String constant forerrennnny String Constant Character Constants are written by enclosing a | ‘String Constants are by enclosing a set of character within a pair of single quotes. characters within a pair of double quotes. Character Constants are assigned to variables oF type” String Constants are assigned to variables of type String. char. (@) Character and Boolean liteFab Character Pernn rr) Character literals are written by enclosing a character A boolean literal can take only one of the two boolean. within 2 pair of single quotes. values represented by the words true or false. Character litefals Catibe assigiiéd to variables of any Boolean literals can only be assigned to variables declared [Link] type = bytey Short, int, long, float, as boolean double, char Escape Sequences can be used to write character Only true and false values are allowed for boolean literals literals Question 10 Write down the data type of the following: (a) Integer : int (c) A fractional number : double (b) Long Integer : long (d) A special character : ehar 13 PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR Question 11 What do you understand by Boolean type data? Explain with an example. A boolean data type is used to store one of the two boolean values — true or false. The size of boolean data type is 8 bits or I byte. Example: boolean bTest = false; Question 12 What do you understand by primitive data type? Give two examples. Primitive data types are the basic or fundamental data types used to declare a variable. Examples of prishiuive Waitajtypes in Java are byte, short, int, long, float, double, char, boolean. Question 13 Why is it necessary to define data type in Java programming? Data types tells Java how much memory it should reserve for storing the value/Data typesalso help in preventing errors as the compiler can check and flag illegal operations at compile time itself. Question 14 Define the following with an example each: (a) Implicit type conversion In implicit type conversion, the result of'a mixed mode expression is obtained in the higher most data type of the variables without any intervention byhetuser, Example: inta= 10; floatb=25.5f, ¢ ¢=a+ bs (b) Explicit type conversion In explicit type conver programmer. For example: mn, the data gets eonverted to a type as specified by the int a= 10; double b = 25.5; float ¢ = (float)(a + b)s Question 15 Define ‘Coercion’ with keference to type conversion. Ina mixed-mode expression, the prdeess of promoting a data type into its higher most data type available in the expression without any interyention by th@juser is known as Coercion Example: byte b = 42; int i = SOO0Rdoubleresult —b ~ i; Question 16 Witatdo you mearf by type conversion? How is implicit conversion different from expli conversion? Thé process Of converting one predefined type into another is called type conversion, In an implicit conversion, the result of a mixed mode expression is obtained in the higher most data type of the variables without any intervention by the user. For example: int a= 10; oRPb = 25.56, ¢; c=a+b; In case of explicit type conversion, the data gets converted to a type as specified by the programmer. For example: int a= 10; double b = 25,5; float ¢ = (floaty(a + b); Question 17 In what way is static declaration different from dynamic declaration? PAATHSHALA INSTITUTE —JAVA COURSE ~ PARV PODDAR 14 In static declaration, the initial value of the variable is provided as a literal at the time of declaration. For example: int mathScore = 100; double p = 14142135; char ch In dynamic declaration, the initial value of the variable is the result of an expression or the return value of a method call. Dynamic declaration happens at runtime. For example: int a= 4; int b = Math,sqrt(a); double x = 3.14159, y = 14142135; double z= y Question 18 What do you mean by non-primitive data type? Give examples. ‘A non-primitive data type is one that is derived from Primitive data types. A number of primitive data types are 86d? together to represent a non-primitive data type. Examples of non-primitive data types in Javajare Class and Array. Question 19 Predict the return data type of the following: int p; double g; r= pte [Link] printhn(r); Answer Return data type is double. (ii) oat m; p = m/3*([Link](4,3)); [Link] printin(p); Answer Return data type is double. Question 20 What are the resultant data typesif the following implicit conversions are performed? Show the result with flow lines. (a) int i; float f; double d; char e; byte b; i+ eb; Answer i+ ¢/b; = int + char / byte = int + char => int (b) fd + of; Answer fi + cf = float / double Achar * Moat => double Piloat = double (i+ fees Answer i+ f- be; = int + float - byte * char = int+ float - char = float - char > float (@) (ffi)*e + bs 15 PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR Answer (ffiJ*e +b; = (float / int) * char + byte > float * char + byte = float + byte = float (@ittet bid; Answer i+ f-¢+ bids = int + float - char + byte / double = int + float - char + double = float - char + double = float + double = double (Oe + tb; Answer i/e + fib => int / char + float / byte = int + float = float ‘Class 10 - Chapter 1- Unit 3 Values and Data Types State whether thefollowing statements are 'True’ or 'False' ion 1 There aré 128 set of different characters used in a Java program Explanation: Jaya uses Unicode which can represent much more than 128 characters 2 The ASCIPeades of upper case letters range from 97 to 122. Explanation ASCII codes of upper case letters range from 65 to 90 Questioin3 A variable gives the exact representation of data. False Explanation: ADliteral gives exact representation of data, As value of variable can change, so it cannot give exact representation of data. ion 4 The data types int, float, char are called non-pri ive types. Explanation: The data types int, float, char are called Primitive types. PAATHSHALA INSTITUTE —JAVA COURSE ~ PARV PODDAR 16 Question 5A Si True Explanation: The data type of the variable that can hold a String literal should also be String, ig literal is assigned to a String variable. Question 6 A character literal is always enclosed in double quotes. False Explanation: A character literal is enclosed in single quotes. Question 7 String constant can be written by using a set of alphanumeric characters. True Explanation: A String literal or String constant is defined by enclosing a set of alphanumeric Characters withimdouble quotes. Question 8 An object is said to be a non-primitive data, True Explanation: Class is a non-primitive data type so Objects are non-primitive data, Question 9 The data type int stores fractional values. False Explanation: float or double data type stores fractiOnall values. Question 10 Boolean type data is used to test a condition and result9jin either true or false. True Explanation: Boolean data type caiibe cithet true or false. Write short answers Question 1 Witatis meant [Link]? Name two types of data type. Answer Data types af@used to identify the type of data a memory location can hold and the associated operations of handling it. Data Types are [Link] types: 1 Primitive Data Types 2. Reference of Composite Data Types Question 2 Why is it necessary to define data type in Jaya pr is? Answer Data types tells Java how much memory it should reserve for storing the value. Data types also help in preventing errors as the compiler can check and flag illegal operations at compile time itself, Question 3 Define the following with an example: (a) variable Answer A variable represents a memory location through a symbolic name which holds a known or unknown value of a particular data type. This name of the variable is used in the program to refer to the stored value. Example: 17 PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR int mathScore = 95; (b) constant Answer The keyword final before a variable declaration makes it a constant. Its value can't be changed in the program. Example: final int DAYS_IN_A WEEK (©) boolean data type Answer A boolean data type is used to store one of the two boolean values —true or false. The size,6f boolean data type is 8 bits of 1 byte, Example: boolean bTest = false; (@) coercion Answer In a mixed-mode expression, the process of promoting a data type into its higher most até type available in the expression without any intervention by the user is known as Coercion. Example: byte b= 42; int i = 50000; double result = b + is (©) pri e data type Answer Primitive data types are the basic or fundamental datatypes usedito declate a variable. Examples of primitive data types in Java are byte, short, int, long, float, doubleyéhar, bootedin, (f) non-primitive data type Answer A non-primitive data type is one that is derived from\Primitive data types, A number of primitive data types are used together to represent a non-primitive data type. Examples of'non-primitive data types in Java are Class and Array. Question 4 What is a token? Name different types dljtokens. Answer A token is the smallest element of a program thatlsteaningful to the compiler. The different types of tokens in Java are: 1. Identifiers 4, Separators 2. Literals 5. Keywords 3. Operators, Question 5 Explain the trm/Aype casting. Answer The process of converting one predefined type into another is called type casting, Question 6 Assign th@following to a variable with suitable data type. (a)m522/7 Answer datible m $(22.0 / 7.0); (b) p= 4142135 (valve of square root of 2) Answer double p = 14142135; (e) k= 0.00008545 Answer double 0.00004545; (@) n=24.50 Answer float n= 24.508; Question 7 Distinguish between: (a) Token and Identifier PAATHSHALA INSTITUTE —JAVA COURSE ~ PARV PODDAR 18 Answer ‘A token is the smallest element ofa program ‘Identifiers are used to name things like classes, that is meaningful to the compiler. objects, variables, arrays, fumetions an so on. (b) Character and Boolean literal Answer Pen 1. Character literals are written by 1. A boolean literal ean take only one of enclosing a character within a pair of the two boolean values represented by single quotes. the words true or false. 2. Character literals can be assigned to 2. Boolean literals ean only be assigned to variables of any numeric data type — variables declared as boolean byte, short, int, long, float, double, char 1 mt 3. Escape Sequences can be used to write 3. Only true and false values are allowed character literals for boolean literals Question 8 Explain the term type conversion. How is implicit conversion diffékent from explicit conversion? Answer The process of converting one predefined type into another is‘Called type conversion. In an implicit conversion, the result of a mixed mode expression is obtained in the higher most data type ofthe variables without any intervention by the user. For example: inta= 10; float b = 25.5f, ¢; c=atb; In case of explicit type conversion, the data gets convertedito a type as specified by the programmer. For example: int a= 10; double float 25.55 float)(a +b); Question 9 Classify the following as‘primitive or nomeprimitive data types. Answer (a) char Primitive (A) clase nowt-primitive Questioni{10 In what way is static initialization of data type different from dynamic initialization? Answer In static initialization, the initial value of the variable is provided as a literal at the time of declarat ‘example: int mathScore = 100; double p = 1.4142135; char ch In dynamic initialization, the initial value of the variable is the result of an expression or the return value of a method call. Dynamic initialization happens at runtime. For example: inta=4; int b= [Link](a); 19 PAATHSHALA INSTITUTE — JAVA COURSE ~ PARV PODDAR double double 3.14159, y = 14142135; ty Question 11 Predict the return data type of 'r' and 'n' from the snippet: int p; float m; r=ptm; n= m/3*([Link](4,3)); [Link](r); [Link](n); Answer Return type of ris float and n is double. Question 12 Give reason whether the following assignments are correct or no (a) int m Answer This assignment is correct as 155 is an integer literal and it is assigned to an int variable m, (b) float f= 0.002654132; Answer This assignment is incorrect as data type of 0.002654132 is double bit itis assigned)to a float variable. The correct assignment will be float f= 0.002654 132f; (o) String str = ‘Computer's Answer This assignment is incorreet as the String literal Computef ig enclosed in Single quotes. It should be in double quotes. The correct assignment will be String str = "Computer" (a) boolean p = false; Answer This assignment is correct as fals a valid boolean literal and)it is assigned to a boolean variable. (©) String b = "true"; Answer This assignment is correct as “true” is a string literal nof@ibodlean literal as itis enclosed in double quotes. It is correctly assigned to a String variable. (f) char ch= "apps"; Answer This assignment is incorrect as "apps" is a string fiteral not a character literal and it is assigned to a variable ch ‘of char data type. (g) String st= "Applicati6Ailts Answer This assignment is correct as "Application" is a string literal and it correctly assigned to a String v. (h) double n = 455,29044 128; Answer This agignment is corfect as 455.29044125 is a literal of double data type and it is correctly assigned to a double variable Ag Tickly) theforrect Option. ,_Which among the following encoding system can represent 65536 characters? a. ASCII b. Unicode ¢.Both a and b d. None of these ‘Ans. b. Unicode 2. Which among the following is not a Token? a. Keywords b. Literals c. Identifiers d. Data Type PAATHSHALA INSTITUTE —JAVA COURSE ~ PARV PODDAR 20 Ans. d. Data Type 3. Which among the following is a keyword but not a literal? a. for b. null c. true d. false Ans. a. for 4, Which among the following is a valid float literal? a. 12.36F b.12.36F ©. 12.36 d. Both aandb ‘Ans, d, Both a and b 5. Which among the following is a valid octal integer literal? a. 0178 b. 675 ©. 0675 . 0X67: Ans, c. 0675 6. Which among the following is a valid method of init a. boolean f=true; 8 c. boolean f="true’; ° Ans. a. boolean f= true; 7. Which among the following is not lator a. ; semicolon b., comma .: colon. d.. dot ‘Ans. c.: colon 8. Which among the fol not a primitive data type? b. float d. char t possible value that can be stored in short data type? b.231-1 d. 263-1 fais of type int and b is of type float what would be the resultant data type of a+b? a. int b. float c. double d. short Ans. b. float B. Fillin the blanks. aa PAATHSHALA INSTITUTE ~ JAVA COURSE ~ PARV PODDAR

You might also like