You are on page 1of 12
Java Building Elements Dr. H. B. Prajapati 30 June 20 Core Java Technology Outline of Presentation @ Console Input and Output Console Input using Command-line Arguments 1[eiaee Greetingat 2] “public static void main(String(] args){ 3 if (arge-length!=1) a Systen.out.printin("Please, pass grooving message"); 5 elset 4 Systen.out.printin ("Helle *+args(0)) 4 Table of contents @ Console input and Output @ entities, Variables, Literals, Data types @ Operators @ Error Handling © Programming Style and Documentation Console Input and Output o-€-o ‘Any program takes same input and produces some out Java associates System out with display and System.in with keyboard Earlier, we have seen that we can generate output in Java program using System.out printn(). We will also lear formated output. Java program can take input in two ways: Command-line arguments (before the program starts execution) f Input at runtime (while program is executing) sony 40 Console Input using Command-line Arguments We test our program with three cases @ No commanel-line arguments @ One command-line argument @ More than one commancb-line arguments SE Console Input at Runtime J program: Pesonnforstion vs ifieport_java-aeit public static void main (String[] arge){ String name; int age; Float weight Scanner. inpu! System. out print name = input nex System. out. print age = input nextint(); System. out. print Weight © input. nexeFle: System. out -printin( Age="*aget”, Wesgh your Ages"); your Weight OF teeight); SS Console Input at Runtime, Running the Program ava progr: Pesonlnformtion va We run the program and input values in wrong data type, Sy Console Output: Formatted Output © Sometimes, we need display/rendering of data in a desired format. 2 Examples: ' Number as right justified to make digits on multiple ines aligned 1 Amount in Rs. (fleat or daube value) has only wo digits afer decimal point 1» Percentage value has only swo digits after decimal point «@ In C language (procedural language). this formating is provided by print() function 1 Java printf) is available as System out printf) (as 100% object oriented, the printf() method is not standalone) ‘The printf) in Java is similar to the printf) in C Console Input at Runtime, Running the Program Jnva program: Perornforstion jv We run the program and input all correct values Console Input Methods Scanner input = nev Scanner (System in); gfint intValue = input nextint J; s]iong lengVaiue = input .nextLong () a]eoubie deubleVaiue ~ input -nextDeuble(); float. fleatVal String string = fe = input. nextFloat 0; input enext Q) 1 In earlier version of Java, Scanner class was not available. We had to use java io package for keyboard input (Will be discussed in Input Output) 9 Java has added Scanner utlty class for console input. Available in java.util package 2 What is a package? Package is 3 grouping concepts, in which we can place related classes under one group. wen Method for Formatted Output 18 The syntax of printf) function is as follows: Syston out printi (format, itesi, ivemd, item); 12 Where the format isa string that may have substrings and format specifiers © A format specifier specifies how an item should be displayed ‘8 An item coulé be 1 numeric (nt long, fost 3 Boolean value fa character oa sting double) ETE SE Format Specifiers 1 A simple specifier has percentage sign (%) followed by one letter character code for the type of éata, Specter Oatpat Danae %; 3 Boolean valve tru or false 2 character 3 2 decimal integer 108 3 number in scenic notation 3.23200008401, 2 floating point number 532.320000 a sting Java is powerful | Specifying Width and Precision @ We can specify wide item to be displayed «8 For floating-point number, we can also specify precision (number of digits after decimal point) 1 In general, width indicates atleast how many characters to be aisplayed: «IF number of characters inthe item lee than the whites space characters are added at the front 1 Othenize, the wicth is meressed to accommodate the characters of the item ples: 2 tiSe: character with total width 8.46 1 8b: boolean with total width 6, ie spaces for tue 2 12s: string of a¢ least 12 characters 0.2: total width of floating-point at least 20 and precision 2 (number of characters to be displayed) for an dd four spaces done space for false and two [—/-—/-~—[~/~/~—-c——oo.- | Program on Formatting output: width and precision ST eso ary Program on Formatting output class Formateeddurpurt public static void main(st int elle = 1 Percent = 78.333333¢ out-printf(*Rell No. %d has it percentage” ,rellNe, percent) ring(] args)¢ ip 1@ The items must match the specifiers in order, in number, and in type. 1 By default, floating-point number is displayed with six digits after decimal point I SS eS Program on Formatting output: width and precision Clacs Foruatved0utputwidehPrecisient public static void main(Sering(] args){ float azount boolean = 48000, eso0seer; fureVisit = false printin('# se RR Ee Ee prince? (“Name :#/105\n" Prinef ("Gender :3¢ U3d\n" gender, age) ; ous. prines ("Pata 120-20 \n" ,anoun printf ("to visit’ in igb\n",futureVasit) Outline of Presentation @ lecntifiers, Variables, Literal, Data types Identifiers © Every entity in the rel world is ident Figure: Sun Figure: Krushna 1 In program also we have to choase names for hings/entities that we want to refer 18 Programming languages use special symbols, called identifiers, for naming programming en a Rules for Naming Identifiers There are rules for naming identifies, lke we have rules for naming persons or objects 18 An identifier must start with a letter (a2,4-Z), an underscore (.), oF 2 dollar sign ($). 1 An identifier cannot contain operators, such as +, -,*, etc 18 An identifier cannot be 2 reserved word 12 An identifier cannot be true, faze, or null 1 An identifier can be of any length CA CT ene aya MMe = = =6hLrtt—<“=‘i™SC;C*@Y Variables © Variables are used to store data for input, output, and intermediate Declaring a variable © Before using a variable, we have to declare it 1 We need to specify bath name and data type forthe variable 1 The syntax is data Type variableName; Example int @ Assignment Statements 1 After a variable is declared, we can assign some value to it 1 The syntax is variableNamne ~ value; orvarialeName = expression; where expression coud be any vali expression or @ method call 1 Example: atea = radiustadius"3.14 12 Combining declaration and initialization ‘We can combine variable declaration and value assignment in single 1 Example: int age = 50, ETE Identifiers 18 We assign names te the folowing programming entities. variables methods classes 1 packages Valid and Invalid Identifiers Valid identifiers 9 82, age, newAge 1 Char, «x (unicode letter allowed) 1X, x (both are different, Java is case sensitive) Invelid identifiers 1 new, flat, cass, private, public. protected isfumbrellafopeni#during#rain| Constants ‘The value of a variable can change during the execution of the program However, the value of a constant, cannot change once assigned Example: final int ENTRY_AGE = 5: Constants declared as class members are made static. Example: static final int ENTRY.AGE = 5; a Numerical Data Types 18 Each data type has a domain(range) of valid values 12 The compiler allocates memary to 2 variable or constant based on its data type «© Java provides several primitive data types for numerical values, characters, and boolean values Daa ype Domain Storage se bye ete ET «i signed shor =28 9241 e-bit signed i 2 to M1 32 bit signed long 2 1 tebe signed float 3.4638 to 43.4638 (6 to 7 sig- 32-bit IEE 754 rificane digits of accuracy) double =L.7E308 to +1.7E308 (14 0 15 64 it IEE 754 Significant digits of aceursey) ET arse sy Numerical Literals 1 A litera isa primitive type value that directly appears in the program 18 For example, 23, 1000000, and 10 0 are literals if ime ay 2] Long 1 = 1000000; a] doubre @ = 10.0; 19 By default floating point number (with decimal point) is considered 5 8 double number 18 We can indicate 2 number literal as float by appending f or F, and Numeric Type Conversion, Slide - | convert the result he expression into 1 Sometimes, we may want some desired data type © For example, converting double result into float or float result into integer. class _NunericTypeConversient public static void main(String[] arge){ 3 Sloat fractien® = 398.5/050; int fractionl = 398.5/450; System. out printin("Fraction in Integer Stractionl); 4 System. out. printin(" “efractionF) raction in Float | double by appending d or D. byte bier = 108 2) Tong War = i 3 + 4; \[_ fleas #2 = 23.08 sL__soubre avar = i+ 3.1'+ 2] double dd = 10.00; CA CT exes nya mince i CC £=—CCcOy ETE aimee 9 Use of Numeric Data Types i= w+; 7 ii becomes 23 a[float €i = 22.02 - 0.12 ai becom ° jJlong 12 = 300¢30 ; becomes d|eoubLe a2 = 1.0/2.0 42 becomes 0.5 sine 43 = 172. 3 be: ofbyte 14 = 2142; es Numeric Type Conversion 18 In an expression a+ b, a and b ate called eperands and + is called © It is possible that operands are of cifferent data types. pes into unifying type. 1 Java chooses unifying type in the following order: double, float, long ine, shor, and byte «9 For example, if one of operands is of type double, the unifying type will be double, Java automatically converts differe Numeric Type Conversion, Slide - II a Numeric Type Conversion, Slide - II 18 We use type casting for converting result of the expression desired/target data type 1 Syntax (target — datatype) expression. tins WunericTypaConversiont public static void main(String (] arge){ float fractionF = (float) 398.5/450; int fractionT = (int) 398.5/450 Systen-outprintin" Fraction actiont); System. out -printin( SfiactionF); in’ Integer action in Float I ETE) ee a = | Character Data Type, Slide - | 12 The character data type, char, is used to represent a single character 1 A character literal is ingicated by enclosing a character in single quotes. [thar grades "a Jensr position = 12's MMe = = =6hLrtt—<“=‘i™SC;C*@Y Unicode Characters, Slide - | Java uses Unicode characters It is 16-bit encoding scheme established by Unicode Consortium Unicode can support interchange, processing, and display of texts of the world languages [As Unicode occupies 2 bytes, Java's character eccupies 2 bytes Unicode literal is indicated using 2-byte hex numbers with \u a5, prefix Unicode range is "\u0000" to *\uFFEF*, in which ASCII code is included in the range "\x0000" to ’\uOOFF? Unicode can be found at he tp://auy unicode.org ETE eS Numeric Type Conversion, Slide - IV 18 The program now compiles successfully and generates the following cutout 18 The resut of the integer fraction is 0 as the fractional part from the result is dropped me Character Data Type, Slide - II 1 An integer value should not be assigned to a character data type cise GharDataTypet public static void main( char position = 63; Syster out. printin(*Position = ang(] args)< position); The output would not be as expected: warn Unicode Characters, Slide - II cines Unieodet public static void main(String(] args)< int k= 72; char charH’= (char) hb; char uni = *\u00a3” Syeten out. printia(*charl uni = "suniH) schari+" a Boolean Data Type 1 The boolean data type is from Boolean algebra 12 The domain of boolean type has only two values: true and false hich are used as literals while assigning value [Peles iewerking mer O—~—S—SSCSY TT Shortcut Operators, Slide - | ‘@ Many times, we want Update value ofa variable by some amount. ipa ea oF 1 We can perform same expression using less characters. ie 20 @ Here, == is called shoreut perator. pester Bample__ Faunvaent Ll _z Shortcut Operators, Slide - III 18 The prefic ++% and sutfix or postix x+-+ are different when they are in expression, 12 The prefix is evaluated before other operators in an expression 18 The postfix or sufix is evaluated after entre expression is evaluated clase PrefisPostfixt public static vold main (String[] args){ int i=0, j=05 int valbre, valPost; valPre = ofa + sti 4 sei + 444; é valPost = jt+ + ptt + jt + jets System. out.printin("Values) i = "+i+" valbre = "+valPre) f) System.out-printin('Values: j= "43+ valbost = "*valPost); a Outline of Presentation © Operators I Se est Shortcut Operators, Slide - II 19 There are two more shortcut operators for incrementing or decrementing by 1 is for incrementing by 2 (is for decrementing by 1 «© Depending upon where (before or after) they are placed along with variable name, there are two types of operation @ Prec +4 © Postine x Shortcut Operators, Slide - IV 18 When we run the program, we get the following output ce It can be observed that after evaluation of expressions, values of both i and j become 4; however, values of valPre and valPost ate different I Comparison Operators ‘2 Comparison operators evaluate to boolean value ‘Upeator Nar Ter = Tess tha re less than or equal to ue areater than false irester than or equal to true ‘equal to false not equal to ue ETE) TT Boolean Operators, Slide - II Boolean Operators, Slide - 18 Boolean operators operate on boolean values and result in a new boolean value Operator Name Description not logis! negation we and logical conjunction i or logical disunetion a exclusive or logical exclusive 12 The not operator (!) is unary operator, whereas other three are binary Boolean Operators, Slide - III ‘Table: Truth values for Operator Ll _z Boolean Operators, Slide - IV 18 When evaluating bi kx 2, Java first evaluates b1 IF Lis false, 82 isnot evaluated IF BL true, then 2 is evaluat €@ When evaluating bl || b2, Java first evaluates bl HF bis tue, b2 isnot evaluated IF BT false, then b is evaluated ‘2 Java provides other operators & and 1 These operators are similar to kk ar || 1 The eitference isin & and |, second operand is also evaluated inespectve of value of the frst operand ETE “Table Truth values for Oper ‘Open —Opwand't —Opern-t | Operant Opeand Tope on on ie * tue fase fie ue ue false te tue fase te “Table Truth values for Operstor kde SE Table: Truth values for Operator ~ Tae Take Tae nad Oper false tue false = true fase fase Boolean Operators, Slide - V class BooleanOperatorst public statse vosd main(S ‘boolean hungry = true; int eatDish = 0; if (aungry ke ore 2) hungry = false 7 if Gaungry ae + 2 @| hungry = false 3| itGhungry @& treatDish >= 2) 0 hungry = false Syates cut printia(*Now hungry Consumed dish "hungry? eatbisan) I Boolean Operators, Slide - VI I EE Boolean Operators, Slide - VIII 12 We should avoid using & and | operators CA CT ease ya Ll _z Operator Precedence, Slide - II “Table: Operater precedence from highest t lowest (pret a aon ent Rn ETE era (2) estiption Figure - Example of Precedence ? Boolean Operators, Slide - VII class DooleanOperators( 2] “public static void main( ‘boolean hungry = false; sng(] args)< she eatDish = 0; if (aungry & steatDish >= 2) falze; 1| & steatdish >= 2) q false 5 b tteatdish >= 2) d| = false; printia(*New hungry = hungry!" eatbish) : Consumed dish = I es Operator Precedence, Slide - | 18 Its possible to write an arbitrary long expression, containing different 18 Operator precedence determines the order in which expressions are evaluated. 1 Parenthesis has highest priority. In nested parenthesis, the innermost parenthesis has highest priority Operator Precedence, Slide - III "Source: An nteducion I nh, Outline of Presentation Errors in Program 1 Even experienced programmer might make mistakes 18 The errors can be categorized into two: Q Compiation Errors © Runtime Erors 12 Compilation errors are reported by compiler Q Error Handling © Runtime errors occur while program is running I ETE) a ee Compilation Errors, Slide - Compilation Errors, Slide - II © Errors that occur during compilation are called compilation errors or syntax errs 18 These are easy to detect as the compiler tells the location and reason 1 Consider the following program ConpilationErrert oJ “public static void main(String(] args) 3 3 = 100; System. out. printin (ira x 12 We can see that the compiler shows errors at two places, where we are accessing variable i 19 The reason for errors is that we have not declared variable j, It should be int i «@ It is possible that for a single error in our program. the compiler shows multiple eros. ©. Therefore, we should start troubleshooting from the fist error oe 57 TT TT ews [EE TT Runtime Errors Runtime Errors 18 An input error occurs when the user enters an unexpected input value land the program cannot handle it © For example, in our earlier program on Personinformation, when we 18 Runtime errors occur while program is running center unexpected value for age, we get runtime error 18 These errors generally cause programs to terminate abnormally (ema 18 Thete are three main reasons for runtime errors @ Input erors @ System software or hardware eros © Logical evors 1» We should provide informative message "Enter your age (integer value) IS st the user. For example, a Runtime Errors Shir Sette oy Harinare Est System errors are rarely encountered owever, sometimes, unreliable system software and hardware ‘malfunctions can cause a program to abort. System errors are beyond programmer's control For mission-critical aplication, system reliability should be achieved ST arse sy a Outline of Presentation @ Programming Style and Documentation [—/Z/Z/iiciuaee=es - — | Appropriate Comments We should place summary at the beginning of the program. {2 The summary can include major information about 2 key features © supporting data structures 1 unique speca logic or algerithes it uses 18 We should write comments before each major step in a long program 12 We should write comments for each complicated or complex part or logic 12 The comments should be concise and easy to read Runtime Errors Logical errrs ether generate incorrect results or terminate the program abnormally, ‘These errors are called bugs. ‘The process of finding logical errors (bugs) is called debugging. Finding logical errors is a dificult task IDES are equipped with debugger, which can be used for step-by-step ‘execution and watching/inspecting values of variables. ‘A-common approach is t and then to reach at the precise cause point. locate code region generating logical errors Programming Style and Documentation Programming style deals with the appearance of the program. It is possible to write the whole program on just one line. However, itis dificult to read and understand; therefore, itis a bad programming style Programming Style and Documentation are as important as coding ‘There are some guidelines for Java programming style and documentation, wr Proper Indentation | © An unindented program is difficult to read 1 Using indentation, we can show structural relationships among the Program's components or statements class Greetingat public static void fi (args. lenge Systen-out printin(*Please, pace greeting message"); elset Systen.out.printin(*Helle "targs[0]); in(String() args) { ST oes sy a Proper Indentation II 1 The following is the same program, but properly indented 18 The program is very easy read and understand 1 class Greevingst public staric void main(String[] args){ it (args length !=1) Syston. out. printin( greeting message elset syst} Lease, pass out. printia (Hello "“+args (0]); Naming Conventions - I! 1 setCustererlane Variables: {similar to methods, the camelCase format should be used (the first letter i loner cae) 1 Short and meaningful names are recommended = Examples: 2 sceountBalance 2 mySting 18 Constants: 1 Java constants are created by marking variable stati an final 1 They should be named using uppercase ltrs with underscore characters a8 separators Examples > MIN EIGHT 12 MA MARKS References {An Introduction to Java Programming, Y. Daniel Liang, PHI @ An Introduction to Java Programming, Y. Daniel Liang, Eigth Edition, Prentice Hall ETE) a Naming Conventions - | 1 Classes and interfaces The fst letter should be capitalized © If several words are linked together to form the name, the first letter of the Inner words should be uppercase «This format is somecimes called carelCase Examples 1 Account 2 Methods 1 The firs letter should be lovercase {Then normal camelCase rules should be used 1 the names should typically be verb-noun pairs = Examples ‘Summary of key terms Scanner (Console input), Command-line arguments Identifiers, variables, constan type, Unicode, Boolean dat numerical data types, character date type Operators: shortcut, comparison, boolean (logical), precedence Error handling: compilation, runtime Indentation, naming convention, comments mine 7

You might also like