Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
41 views
30 pages
Section2 Primitive+data+types+in+Java
Primitive data
Uploaded by
sbrlearning955
AI-enhanced title
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
Download
Save
Save Section2_Primitive+data+types+in+Java For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
41 views
30 pages
Section2 Primitive+data+types+in+Java
Primitive data
Uploaded by
sbrlearning955
AI-enhanced title
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
Carousel Previous
Carousel Next
Download
Save
Save Section2_Primitive+data+types+in+Java For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Section2_Primitive+data+types+in+Java For Later
You are on page 1
/ 30
Search
Fullscreen
eaz} bytes Keywords in Java In Java, a keyword isa reserved word that has a specific meaning and purpose in the programming language. These keywords cannot be used as identifiers (such as variable names or method names) in the code because they are already predefined with ‘particular function in the Java language. Some examples of keywords in Java include: interface extends, implements import Java syntax requires all code, including keywords, to be case-sensitive. Therefore, an “public” with all lowercase letters is not ‘equivalent to "Public’ with a capital letter, as they have different meanings. It's important to note that "public" is a keyword in Java.eaz} bytes Java Primitive Data Types All the values in Java are divided into two categories: reference types and primitive types. We can start with primitive types and operators as they are most basic and natural entry into Java © OVERVIEW DATA TYPES Java supports eight basic data types known as primitive types. The primitive types include a boolean type,a character type, four integer types, and two floating-point char boolean types. The four integer types and the two floating-point types differ in the number of bits that represent them byte and therefore in the range of numbers they can represent/aupport.Why we need Primitive Data Types ? bytes ‘Think a scenario where your friend asked to subtract two number. He told the first number as 30 and the second number as 10 You will store the number details inside your brain memory and perform subtraction. If ‘asked, you can perform addition or ‘multiplication ete. based on the same numbers Just like how we store data inside brain memory, computers also has to store them inside it's memory. To help around this, we have Primitive data types in Java scrunber 30 conan 10 Since computers can't think themselves, we need to follow various syntaxes, rules while trying to store data using primitive data typesdefault eaz! bytes type size range Deolean fase re ms char ‘00 oie /2Byte8 te arr inte ° sbits/1 Bye seater short ° tote /2Byte8 saree oster mt ° eit /4By08 sereseanw ners tong ° tit / 808 ~suzsriseserize ‘oat °0 sabi Bytes se astosaneeseee double 09 64bita/8 Bytes naredsiseessieresee Java Primitive Data TypesSYNTAX TO DECLARE PRIMITIVE DATATYPES? byt Primitive datatype Literal Primitive datatype variable a 4 so 1 t t oY 1 1 too int i,j = 8; double num; a a) varlable/identiter t Only Dectaration but if ‘0 initialization varablos SD) sotn Declaration & initialization Y ‘he representation ofa value i called a literal. They include integer and floating-point numbers, single characters within JX, S98 ts ered rote Fr een oieazy HOWTO NAME A VARIABLE ? bytes ‘Variable names ae case-sensitive and can bo formed using alphabiors,numbers,"S", "Thay an gel started with alter the ‘When choosing aman for your variables, use fall words instead of erypte abbreviations. Doing 30 will make your code easier to read ‘and understand In many cases til also make your cod self documenting, fields versions, suchas .s,and.g Also keep in mind thatthe name you choose must not be & keyword or reserved wordeazy Examples of valid & invalid identifiers ? bytes frstNamet Yee Contes tters a number Spersnhame ves Can start with, _anda eter rstName No Can not star with number an = Conia aoe rs Contains space in between the nee eee creer mi = Contos“ which sat allowed - Only $ and are allowed 3 Yes Only $s ali allowed name nce DKS the use ofan underscore ass - = standalone identifier is no longer permitted 5 Though sna flow odes S CamelCase stil vai es Ne Using all embers isnot allowed in Java programs, Une words-true false, nd null-might seem like keywords, but they aren't Instead, true and false function as Boolean iterals while nll serves asa pul itera. I's important to note that despite not being keyword, true false. and nul cannot be employed a5. correoeazy Case Styles in programming bytes In programming, naming conventions are crucial as they help in writing more readable and maintainable code, One aspect of these conventions is case styles, which determine how to format variable, function, method and class names. Case styles refer to the way you use capitalization and spacing to differentiate between words in a name. To create a variable in your program with a name that consists of more than one word, you must combine the words into a single string and remove any spaces between them, Failure to do go may cause your program to crash, Most programming languages have specific naming conventions for combining words in variable names. For example, ‘you can't create a variable like below, number of players camelCase PascalCase snake case kebab-case (Camel case involves starting witha Pascal case and camel cas ae similar, Snake case ivcives using an Kebab cas is quite sinilarto make lowercase letter or thefiest word withthe oly distinction being that underscore character ()1oepaate —_catoexcop htt uses dash andthencapitaling he fistleter _pascatease mandates thefistleter of gachwordimavariale name, Thia character. separate each word ‘feachsubsequentword This theft word tobe capitalized. in pateal naming convention is commonly ina variable name instond of an reanathat each new word afrthe case, every word begins with an ‘sed to decare constants underscore, This naming convention fiethas.capitaletter atthe wppercase letter as opposed to camel programminglanguages when requires all word o be in lowercase beginning. is commonly wsedin caso, where theirat word begins witha capitalized itis commonly usodin __—andseparated by a dash Kebab JivaScriptand ava programming lowercase letter tis commonly wsedn_JavaPyihon and Ruby programming. cates commonly used in URL and # and NET programming. os. number of players, numberO{Players, 3 furstame nurmOrPeopte, SemberOmeyer rr——C es FirstName,NumOfPeople, ‘email address, = EmailAddress NUMBER OF PLAYERSThe boolean type ‘The boolean type represents truth values. This type has ony two possible values true & false, They represent the two boolean etter such as on oro, Yet of note oF false ete Java reserve the words true and false to represent these two Boolean values A boolean variable is typically used in control flow statements, which we ‘0 going to discuss inthe coming eaz} bytes Sample declaration of boolean variables & values, boolean hasChildren; boolean isValid = true; boolean isMajor, hasPassport ue; Sample code snippet in jshell, rere Fosre scares |jshell> systen.out printin(isvalid); Foaores | Using the prefix ‘ifr a boolean variable name ie a common practice among ovelopers, asithelps to create a name that appears ike a question and makes th code teaser to vead and understand. Howaver,there are other prefies that ean be weed for boolean variable names that are also acceptable and validThe char type ‘The char datatype is used to store a single character The character must be ‘surrounded by single quotes, ico M! ‘The char datatypes a single 16-bit Unicode character Its value range lise Dettween \u000d (or 0) to uf (or 65,538 inclusive) The char datatype is ‘sed to stove characters ‘Unicode isa universal international standard character encoding tha iz capable ofrepresenting most ofthe world’s witen languages eaz} bytes Sample declaration of char variables & values, char num charx char x1 char y; char z= 456; Sample code snippet in jshell, Bee ae ane F M POPE CURT a sus uico rseazy The char type bytes ‘The char type isan unsigned integer that ean hold a vale (called a code point from to 105,695 incusive. Itropresente a Unicode character, which means thre ae 65.535, Unicode characters. For example, if you y to ‘um 2 char variables char valuo is ‘epresented by ts code point. ‘The Character clas defines number of ‘useful static methods for morkang with characters, including isDigit),isLowerC3s00, ‘and toUpperCaze0 ete Fow sample escape sequences & their representation valu, \b- Backspace, \t- Horizontal tab, \n - Newline, \- Form feed, \r- Carriage return," - Double quote, V Single quote, \-The Integer types Integer types stores whole mimbers, positive or negative (euch aa 168 or 13), wnthout decimals Vali types are hye short, intand long, Which type you should tse, depends onthe size of smumerio valve Since ther is overlap between int ype literals and ong type literals, an Intogor literal of ype long always ends wih L (or lowercase. ‘We can always fotch the min and max ‘values supported by these datatypes ‘using MIN. VALUE & MAX VALUE state variables avadable in the reapective cassos ike Byte, Short, Integer & Long, eaz} bytes Sample declaration of Integer variables & values, byte bl = 127, b2 = 1; short s = 3244; intx=10; Jong num = 4561; ‘Sample code snippet in jshell, PRISE mee eee) Gere Cua ets CTThe Integer types “ Size & Range of numeric values need to be considered while choosing one of the interger data types.eazy Importance of Lsuffix bytes In Java, the L suffix is required to indicate a long literal. By default, integer literals are of the int type, which can represent values between -2,147,483,648 and. 2,147,483,647. If you want to represent a value that is outside this range, you need to use a long literal instead. A long literal is a whole number that ends with the letter L (lowercase or uppercase) or | (lowercase only). For example: long longvalue = 1234567890123L; In the example above, the . suffix is required to indicate that the value 1234567890123 should be treated as a long literal, rather than an int literal. Without the L suffix, the compiler would interpret the value as an int literal and generate a compiler error, since the value is outside the range of the int data type.Overflow and Underflow bytes In Java, overflow and underflow refer to situations where the result of an arithmetic operation exceeds the range of the data type being used. Java compiler can detect the overflow or underflow scenarios if we try to assign a value directly that is either greater than max value or less than min value. Ant overFlowifum = 2147483648; // 1112 not compile due te overflow int underFlowNum = =2147483649; // wii not compile due to undestiow Overflow occurs when the result of an arithmetic operation exceeds the maximum value that can be represented by the data type. For example, if an int data type is used to store a value of 2,147,483,647 and 1 is added to it, the result will overflow and wrap around to the minimum value of -2,147,483,648. int overFlowNum = 2147483647 + 1; // mitt compile ¢ zeruit in overtiowOverflow and Underflow bytes Underflow occurs when the result of an arithmetic operation is less than the minimum value that can be represented by the data type. For example, if an int data type is used to store a value of -2, 147,483,648 and 1 is subtracted from it, the result will underflow and wrap around to the maximum value of 2,147,483,647. int underFlowium = -2147483648 - 1; /7 wait comptie ¢ result sn underflow Since the compiler does not evaluate the expressions during compile time, it cannot detect these scenarios and will not issue any warnings or errors related to overflow or underflow. It is up to the programmer to ensure that the values being used in the arithmetic expressions are within the acceptable range for the data type being used, and to handle any potential overflow or underflow scenarios in the code. This can be achieved through various techniques such as using larger data types to accommodate larger values, validating user input, and implementing checks to detect potential overflow or underflow scenarios.eazy The Floting point types bytes ‘Sample declaration of Floating point variables & values, Real or decimal numbers in av represented by the float ana double cata types. decimal digits where as with double wwe can sore up to 15 docimal digits Semeninend nee pee TatgaeaTTs ‘Wo can alrays fetch the min and max. ‘values upporied by these datatypes ‘sing MIN VALUE & MAX VALUE ‘tate variables avaiable inthe respective clasoas like Flat & Double BRU eb eC ae eee f 33.3 To indicat that you would like itto be tteated as afloat type, forall the float {ters ou need to add either For F BUSS CR
) Write Down Powers of 2: 2 ) starting from the rightmost digit, write down powers of 2for each position. The rightmost digit corresponds to 2, the next digit to 2! —~ and goon. () Multiply and Sum to calculate decimal value: (3 ) muttipty each binary digit by the corresponding power of 2 and sum the results to get the decimal value. Here's an example to ilustrate the process to convert the octal number 1101;0r 0B1101 into decimal, (1x29)+(0x21)+(1x22) +(1x23) 404448 S0,1101gin binary is equa to 199 in decimal Output sample from Java: BRIE SULTS ae SECS Cran d 13Type Casting in Java bytes When we assign a value of one primitive data type to another type, we call it as type casting. In Java, there are two types of casting: Widening Casting (automatically/implicit) - converting a smaller type to a larger type size It is done automatically & safe because there is no chance to lose data. byte > short-> char -> int-> long -> float-> double Narrowing Casting (manually/explicit) - converting a larger type to a smaller size type. It should be done manually by the programmer. If we do not perform casting then the compiler reports a compile-time erzor. double -> float -> long -> int -> char > short -> byteType Casting in Java bye int mylntNum = 16; double myDoubleNum = mylntNum; Asta xing tom inti doable ‘System.outprintin(mylniNum): //oxeas 18 ‘System.outprintin(myDoubleNum); //oupat 160 ore Goatees potest st eircrty Greens tania Sore Osea te Rte osiorS cy ‘boolean fo other data types casting is not possible asthe supported values are differentType Casting in Java double myDoublePiNum = 3.144; int mylntPiNuum = (int) myDoublePiNum; Aan! eeting dob tnt ‘System.out,printingmyDoublePiNum);, //oxpues.1¢ ‘System.out printincmylatPiNum);—// oats 3 Peerersrnenserey InyDoubePiNum ==> 3.34 Pere eC tstts eerie) Oe nea USCC SL ‘RequiredDatatype Variable! = (TargetType) Variable2; Eph Pe eas econo sty B Pate |Type Casting in Java Ce int numI = 13; ong nurm2 = 21474836401; / mbes oie enge num] = num; compe tine err og osama ort ‘numm] = (nt) numa; sear tetra in veto int num] = 6; Jong num2 = 361; rum] = num; /conpie-tme aor Een md vate 95. herane ot bytes More examples int num] = 2000; float numa = 2314.23F; ‘urn = num; comet eer: Cant ign Ba ot zmurnl = (int) num@; // OX sum wi tre 2314 ‘int num! = 1498764585; float numa = nul: {nt num = (int) numa; ‘You apt al be ave Bid ua mdse etc Neer, ong ch raf nfo ae aed tal ogg uber cab Septet any nn rc aon yoo) ‘char charValue = int intValue = charValue; ma oie 6beca caring achat at “apyThe String types InJava.a String is a sequence of characters, Iti an object that represents a series of characters and provides a wide range af methods 0 manipulate and wor with sings, For example, the string "Java consist ofthe four characters]. a, a Wie have just described the primitive value typet ofthe Java language. All the ‘other value types in Java inctading Sting belong ta category of reference typer way to create txtin Java They are ‘croated by enclosing a series of characters main dowble quotes Aroterence ype is s.called because, the code, edo ol deal with values ofthe ype dec A vale of erence type it more complex ha eaz} bytes [Any reference class can refer to a null literal. t represents a reference value that does not point to any object. In the case of ‘String type, it looks like below: String input = null; ‘Sample declaration & initialization of String, String input = “Hello World 1"; ‘Sample code snippet in shel, jshell> String input = "Hello World 1"; Foose Sess t Pte none u tec a Lotennsth jshell> ‘umlive-ype value Iie caled an objec and requles ore complex mamory allocation, eo a oference-ype variable contain a memory relerence, pols lor) othe merry aoa hare the joc fesies, hance the mame, We wil ducior more abou Claas & Objects cong lost
You might also like
GOLD Core Java Durga Sir - Java - Notes - Teachmint
PDF
No ratings yet
GOLD Core Java Durga Sir - Java - Notes - Teachmint
459 pages
Java Buzzwords
PDF
No ratings yet
Java Buzzwords
58 pages
Fundamentals of Programming in Java
PDF
100% (1)
Fundamentals of Programming in Java
34 pages
Chapter 2 Basics in Java Programming
PDF
No ratings yet
Chapter 2 Basics in Java Programming
42 pages
Jaca Docx3
PDF
No ratings yet
Jaca Docx3
42 pages
SCJP Core Java Blaze
PDF
No ratings yet
SCJP Core Java Blaze
250 pages
Part 01 - Java Basics 1 - Variable
PDF
No ratings yet
Part 01 - Java Basics 1 - Variable
56 pages
Chapter 2
PDF
No ratings yet
Chapter 2
50 pages
Student JF 4 3 SG
PDF
No ratings yet
Student JF 4 3 SG
61 pages
Java Basics
PDF
0% (1)
Java Basics
51 pages
Unit 2 Programming Basics (Tapashi Final) Edited
PDF
No ratings yet
Unit 2 Programming Basics (Tapashi Final) Edited
18 pages
2-Data Types (E-Next - In)
PDF
No ratings yet
2-Data Types (E-Next - In)
19 pages
Data Types Keywords Identifiers
PDF
No ratings yet
Data Types Keywords Identifiers
13 pages
College of Science Department of Computer Programing Fundamentals (Java) First Stage
PDF
No ratings yet
College of Science Department of Computer Programing Fundamentals (Java) First Stage
26 pages
SCJPBy Nagaraju
PDF
No ratings yet
SCJPBy Nagaraju
250 pages
Java Variables Types
PDF
No ratings yet
Java Variables Types
32 pages
Lesson 3
PDF
No ratings yet
Lesson 3
12 pages
Class 9 Notes
PDF
No ratings yet
Class 9 Notes
15 pages
Elementary Java Programming
PDF
No ratings yet
Elementary Java Programming
214 pages
03 Primitive Datatypes
PDF
No ratings yet
03 Primitive Datatypes
41 pages
Module 2
PDF
No ratings yet
Module 2
40 pages
JAVA - 3 - Data Types Variables and Arrays
PDF
No ratings yet
JAVA - 3 - Data Types Variables and Arrays
50 pages
Java Variables and Types
PDF
No ratings yet
Java Variables and Types
12 pages
Chapter 5 (Concept of Data Type)
PDF
No ratings yet
Chapter 5 (Concept of Data Type)
10 pages
ch02 PDF
PDF
No ratings yet
ch02 PDF
119 pages
Java Datatype, Variables, Operators, Keywords, Naming Convention Notes
PDF
No ratings yet
Java Datatype, Variables, Operators, Keywords, Naming Convention Notes
18 pages
Unit 03 - Data Types and Variables
PDF
No ratings yet
Unit 03 - Data Types and Variables
2 pages
TQA2023 2024 JavaVariablesTypes Part1
PDF
No ratings yet
TQA2023 2024 JavaVariablesTypes Part1
13 pages
Java Programming Chapter 1
PDF
No ratings yet
Java Programming Chapter 1
149 pages
2 Lecture Two
PDF
No ratings yet
2 Lecture Two
61 pages
Chapter 2
PDF
No ratings yet
Chapter 2
26 pages
JAVA
PDF
No ratings yet
JAVA
5 pages
Hands Out 1
PDF
No ratings yet
Hands Out 1
6 pages
Lesson 2 Java Fundamentals
PDF
No ratings yet
Lesson 2 Java Fundamentals
52 pages
Programming Building Blocks - Java Basics
PDF
No ratings yet
Programming Building Blocks - Java Basics
51 pages
Data Type in Java
PDF
No ratings yet
Data Type in Java
6 pages
3 Lecture 3 Variable & Keywords
PDF
No ratings yet
3 Lecture 3 Variable & Keywords
36 pages
Core Java Ex 1
PDF
No ratings yet
Core Java Ex 1
157 pages
Java Basic Structure, Identifiers, Data Types and Operators
PDF
No ratings yet
Java Basic Structure, Identifiers, Data Types and Operators
8 pages
Topics To Be Covered:: Unit - 2
PDF
No ratings yet
Topics To Be Covered:: Unit - 2
52 pages
02 - Development Software For Mobile
PDF
No ratings yet
02 - Development Software For Mobile
46 pages
CSE102 - Week2
PDF
No ratings yet
CSE102 - Week2
34 pages
Language Fundamentals
PDF
No ratings yet
Language Fundamentals
23 pages
Lect 3
PDF
No ratings yet
Lect 3
42 pages
DataType VariablCasting Operators
PDF
No ratings yet
DataType VariablCasting Operators
38 pages
Java Language Fundamental by Druga Sir
PDF
No ratings yet
Java Language Fundamental by Druga Sir
48 pages
Java Notes 2
PDF
No ratings yet
Java Notes 2
8 pages
Java
PDF
No ratings yet
Java
389 pages
Java Programming Constructs
PDF
No ratings yet
Java Programming Constructs
32 pages
Java Data Types
PDF
No ratings yet
Java Data Types
14 pages
Reference Material - 03. Values and Data Types
PDF
No ratings yet
Reference Material - 03. Values and Data Types
5 pages
Data Types in Java and Opearator and Separators
PDF
No ratings yet
Data Types in Java and Opearator and Separators
22 pages
Java Basic 1
PDF
No ratings yet
Java Basic 1
9 pages
Javanotes5 41 50
PDF
No ratings yet
Javanotes5 41 50
10 pages