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)
118 views
GOLD Core Java Durga Sir - Java - Notes - Teachmint
Uploaded by
xenav27017
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save GOLD Core Java Durga Sir - Java - Notes - Teachmin... For Later
Download
Save
Save GOLD Core Java Durga Sir - Java - Notes - Teachmin... For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
118 views
GOLD Core Java Durga Sir - Java - Notes - Teachmint
Uploaded by
xenav27017
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save GOLD Core Java Durga Sir - Java - Notes - Teachmin... For Later
Carousel Previous
Carousel Next
Save
Save GOLD Core Java Durga Sir - Java - Notes - Teachmin... For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 459
Search
Fullscreen
Language Fundamentals 1. Identifiers 2. Reserved words 3. Data types 4. Literals 5. Arrays 6. Types of variables 7. Var arg method 8. Main method 9. Command line arguments 10. Java coding standards Identifier: A name in java program is called identifier. It may be class name, method name, variable name and label name. Example: lass 1 4 a wublic static void main(Stringl] are cere mpr t rT 2 34 )5 Rules to define java identifiers: Rule 1: The only allowed characters in java identifiers are: 1) atoz 2) AtoZ 3) Otod 4) 5) $ we are using any other character we will get compile time error. Example: Example: 1) ABC123: lid 2) 123ABC- invalid Rule 4: java identifiers are case sensitive up course java language itself treated as case sensitive language.Example: class Test{ int number=10; int Number=20; int NUMBER=20; [we can differentiate with case. int NuMbEr=30; } Rule 5: There is no length limit for java identifiers but itis not recommended to take more than 15 lengths. Rule 6: We can’t use reserved words as identifiers. Example: int if=10; Rule 7: All predefined java class names and interface names we use as identifiers. Example 1: class Test { public static void main(String{] args){ int String=10; System. out. printin(String); n Output: 10 Example 2: class Test { public static void main(String{] args){ int Runnable=10; System.out.printin(Runnable); wt Output: 10 Even though it is legal to use class names and interface names as identifiers but it is not a good programming practice. Which of the following are valid java identifiers? invalid1)_$_(valid) 2)CaSh(valid) 3)lava2share (valid) 4)all@hands(invalid) 5)123abc (invalid) 6)Totald (invalid) ‘hint invalid) 8)integer (valid) Reserved words: ‘+ In java some identifiers are reserved to associate some functionality or meaning such type of reserved identifiers are called reserved words. Reserved words(53) LUiterals(3 true. Falues Tor bootean| tat (default value For null—lobject reference, fals Used keywords (48) | —soto {const Reserved words for data types: 1) byte 2) short 3) int 4) long 5) float 6) double 7) char 8) boolean Reserved words for flow control: a) if 2) else 3) switch 4) case 5) default 6) for 7) do8) while 9) break 10) continue 11) return Keywords for modifiers: 1) public 2) private 3) protected 4) static 5) final 6) abstract 7) synchronized 8) native 9) strictfp(1.2 version) 10) transient 11) volatile Keywords for exception handling: y ty 2) catch 3) finally 4) throw 5) throws 6) assert(1.4 version) Class related keywords: 1) class 2) package 3) import 4) extends 5) implements 6) interface Object related keywords: a) new 2) instanceof 3) super 4) this Void return type keyword: ‘© If amethod won't return anything compulsory that method should be declared with the void return type in java but itis optional in C++1) void Unused keywords: goto: Create several problems in old languages and hence it is banned in java. Const: Use final instead of this, ‘© By mistake if we are using these keywords in our program we will get compile time error. Reserved literals: 1) true | values for boolean data type. 2) fast 3) nul Enui ‘* This keyword introduced in 1.5v to define a group of named constants Example: enum Beer { KF, RC, KO, FO; } Note: All reserved words in java contain only lowercase alphabet symbols. New keywords are: - default value for object reference. Which of the following list contains only java reserved words? 4) final, finally, finalize (invalid)//here finalize is a method in Object class. 2) throw, throws, thrown(invalid)//thrown is not available in java 3) break, continue, return, exit(invalid}//exit is not reserved keyword 4) goto, constant{invalid)//here constant is not reserved keyword 5) byte, short, Integer, long(invalid)//here Integer Is a wrapper class 6) extends, implements, imports{invalid)//imports keyword is not available in java 7) finalize, synchronized(invalid)//finalize is a method in Object class 8) instanceof, sizeOf{invalid)//sizeOf is not reserved keyword 9) new, delete(invalid)//delete is not 2 keyword 10) None of the above(valid) Which of the following are valid java keywords? 1) public(valid) 2) static(valid) 3) void(valid) 4) main(invalid) 5) String(invalid) 6) args(invalid)Data types: Every variable has a type, every expression has a type and all types are strictly define more over every assignment should be checked by the compiler by the type compatibility hence java language is considered as strongly typed language. Java is pure object oriented programming or not? ‘* Java is not considered as pure object oriented programming language because several oops features (like multiple inheritance, operator overloading) are not supported by java moreover we are depending on primitive data types which are non objects. ram primitive data types(8) Numeric datatypes char datatypes boolean data types (to represent numbers) (to represent characters) (to represent logical values) Integral data types floating point data types (to represent whole (to represent real numbers) ‘umbers) byte short Sint float double [Ione ‘+ Except Boolean and char all remaining data types are considered as signed data types. because we can represent both “#ve” and”.ve” numbers. Byte: Size: Lbyte (Sbits) Maxvalue: +127 Minvalue:-128 Range:-128to 127[-2’ to 2’-1] msg (EEE P EELS signbit 26*1425*1424*1423*1+22"1421"1+20"2 oo (+ve) 64*1+32*1416*148*144*142"141*1 1 (ve) 4127 ‘© The most significant bit acts as sign bit. “O” means "+ve” number and “1” means “-ve” number, ‘+ “tve" numbers will be represented directly in the memory whereas “-ve” numbers will be represented in 2's complement formExample: byte b=10; byte b2=130;//C.E:possible loss of precision byte b=10.5;//C.E:possible loss of precision byte betrue;//C.E:incompatible types byte b="durga’',//C.E:incompatible types ‘© byte data type is best suitable if we are handling data in terms of streams either from the file or from the network Short: ‘© The most rarely used data type in java is short. Size: 2 bytes Range: -32768 to 32767(-2"° to 2-1) Example: short s=130; short s=32768;//C.E:possible loss of precision short s=true;//C.E:incompatible types © Short data type is best suitable for 16 bit processors like 8086 but these processors are completely outdated and hence the corresponding short data type is also out data type. int ‘© This is most commonly used data type in java. Size: 4 bytes Range:-2147483648 to 2147483647 (-2"' to 2"-1) Example: int i=130; int i=10.5;//C.E:possible loss of precision int i=true;//C.E:incompatible types tong: © Whenever int is not enough to hold big values then we should go for long data type. Example: ‘* To hold the no. Of characters present in a big file int may not enough hence the return type of length() method is long. long lengthi);//is a file Size: 8 bytes Range:-2" to 2-1 Note: All the above data types (byte, short, int and long) can be used to represent whole numbers. If we want to represent real numbers then we should go for floating point data types. Floating Point Data types: float double 1) If we want to 5 to 6 decimal places of | 1) ‘If we want to 14 to 15 decimal places accuracy then we should go for float of accuracy then we should go for double. 2) Size:4 bytes. 2), Size:8 bytes. 3) _Range:-3.4e38 to 3.4e38, 3)_-1.7e308 tol.7e308.4) float follows single precision 4) double follows double precision. boolean data type: Size: Not applicable (virtual machine dependent) Range: Not applicable but allowed values are true or false. Which of the following boolean declarations are valid? Example. boolean b=true; boolean //C.E:cannot find symbol boolean b="True";//C.E:incompatible types boolean b=0;//C.E:incompatible types while(i) { ‘Systom.out.printin(*hello”); Char data typ ‘© In java we are allowed to use any worldwide alphabets character and java is Unicode based to represent all these characters one byte is not enough compulsory we should go for 2 bytes, Size: 2 bytes Range: 0 to 65535 Example: 35536;//C.E:possible loss of precision Summary of java primitive data t data type size Range Corresponding | Default value Wrapper class byte ibyte -2to2-1 Byte 0 (-128 to 127) short 2 bytes 2° tol 1 Short 0 (-32768 to 32767) int bytes 2 toe Integer 0 (-2147483648 to 2147483647) long 8 bytes 25 to 2 Long 0 float 4 bytes “3.4€38 to Float 0.0 3.4038double S bytes -1.7€308 to Double 0.0 1.72308 boolean Not applicable | Not Boolean false applicable(but allowed values true| false) char 2 bytes Oto 65535 Character Ofrepresents blank space) ‘© The default value for the object references is “null”. Literals: ‘© Any constant value which can be assigned to the variable is called literal. Example: int x 0 Ls constant value tit name of variable |identifier datatype keyword Integral Literals: For the integral data types (byte, short, int and long) we can specify literal value in the following ways. 1) Decimal literals: Allowed digits are 0 to 9. Example: int x=10; 2) Octal literals: Allowed digits are 0 to 7. Literal value should be prefixed with zero, Example: int x=010; 3) Hexa Decimal literals: The allowed digits are 0 to 9, A to Z. For the extra digits we can use both upper case and lower case characters. This is one of very few areas where java is not case sensitive. Literal value should be prefixed with ox(or)oX. Example: int x=0x10; ‘+ These are the only possible ways to specify integral literal. Which of the following are valid declarations? 1) int x=0786;//C.E:integer number too large: 0786(invalid) 2) int x=OxFACE;(valid) 3) int x=Oxbeef;(valid) 4) int x=OxBeer;//C.E:’;' expected(invalid) Uf:int x=OxBeer; Oxabb2cd;(valid) int int y=010; int 2=0x10; System.out.printin(x+"=-—"+y+"-—-"42); //10~ 16 © By default every integral literal is int type but we can specify explicitly as long type by suffixing with small "I" (or) capital "L”Example: int x=10;(valid) long l=10L;(valid) long I=10;(valid) int x=101;//C.E:possible loss of precision(invalid) ‘* There is no direct way to specify byte and short literals explicitly. But whenever we are assigning integral literal to the byte variables and its value within the range of byte compiler automatically treats as byte literal. Similarly short literal also. Example: byte b=10;(valid) byte b=130;//C.E:possible loss of precision(invalid) short s=32767;(valid) short s=32768;//C.E:possible loss of precision(invalid) Floating Point Literals: Floating point literal is by default double type but we can specify explicitly as float type by suffixing with f or F. Example: float f=123.456;//C.E:possible loss of precision(invalid) float f=123.456f;(valid) double d=123.456;(valid) ‘© We can specify explicitly floating point literal as double type by suffixing with d or D. Example: double d=123.456D; ‘+ We can specify floating point literal only in decimal form and we can’t specify in octal and hexadecimal forms. Example: double d=123.456;(valid) double d=0123.456;(valid) double d=0x123.456;//C.E:malformed floating point literal(invalid) Which of the following floating point declarations are valid? 1) float f=123.456;//C.E:possible loss of precision(invalid) 2) float f=123.456D;//C.E:possible loss of precision(invalid) 3) double d=0x123.456;//C.E:malformed floating point literal(invalid) 4) double d=OxFace;(valid) 5) double d=OxBeef;(valid) ‘* We can assign integral literal directly to the floating point data types and that integral literal can be specified in octal and Hexa decimal form also. Example: double d=OxBeef; System.out. printin(d);//48879.0 ‘© But we can’t assign floating point literal directly to the integral types. Example: int x=10.0;//C.E:possible loss of precision ‘+ We can specify floating point literal even in exponential form also(significant notation), 10Example: double d=10e2;//==>10"10°(valid) System.out.printin(d);//1000.0 float f=10e2;//C.E:possible loss of precision(invalid) float f=10e2F;(valid) Boolean literals: The only allowed values for the boolean type are true (or) false where case Is important. Example: 1) boolean b=true;(valid) 2) boolean b=0;//C.E:incompatible types(invalid) (C-E:cannot find symbol(invalid) //C.E:incompatible types(invalid) 4) boolean b="true’ Char liter 1) Achar literal can be represented as single character within single quotes. Example: 1) char ch='a';(valid) 2) char ch=ai//C.E:cannot find symbollinvalid) 3) char ch="a";//C.E:incompatible types(invalid) 4) char ch='ab';//C.E:unclosed character literal(invalid) 2) We can specify a char literal as integral literal which represents Unicode of that character. We can specify that integral literal either in decimal or octal or hexadecimal form but allowed values range is 0 to 65535. Example: 1) char ch=97;(valid) 2). char ch=OxFace; (valid) System.out.printin(ch);//? 3) char ch=65536;//C.E: possible loss of precision(invalid) 3) We can represent a char literal by Unicode representation which is nothing but “\uxxx’ Example: 1) char ch1="\u0061"; System.out.printin(ch1);//a 2) char ch2=\u0062;//C.E:cannot find symbol 3) char ch3='\iface';//C.E:illegal escape character 4) Every escape character in java acts as a char literal. Example: 2) char ch="\n'//{(valid) 2)_ char ch="\V//C.E:illegal escape character(invalid) Escape Character Description \n New line \t Horizontal tab \r Carriage return \f Form feed \b Back space character aV ‘Single quote \ Double quote WV Back space Which of the following char declarations are valid? 1) 2) 3) 4) 5) 6) char ch=a;//C.E:cannot find symbol{invalid) char ch='ab’;//C.E:unclosed character literal{invalid) char ch=65536;//C.E:possible loss of precision(invalid) char ch=\uface;//C.E:illegal character: \64206(invalid) char ch="/n';//C.E:unclosed character literal(invalid) none of the above.(valid) String literals: Any sequence of characters with in double quotes is treated as String literal Example: String s="bhaskar”;(valid) Diagram: 1) 2) 3) 4) 5) 6) 7 8) 9) byte—> short A int —> long —> float —>double char. Arrays Introduction Array declaration Array construction Array initialization Array declaration, construction, initialization in a single line. length Vs length() method Anonymous arrays Array element assignments Array variable assignments. An array is an indexed collection of fixed number of homogeneous data elements, The main advantage of arrays is we can represent multiple values with the same name so that readability of the code will be improved. But the main disadvantage of arrays is: Fixed in size that is once we created an array there is no chance of increasing or decreasing the size based on our requirement that is to use arrays concept compulsory We should know the size in advance which may not possible always. We can resolve this problem by using collections. Array declarations: Single dimensional array declaration: 2Example: int{] a://recommended to use because name is clearly separated from the type int (a; int all; ‘© At the time of declaration we can’t specify the size otherwise we will get compile time error. Example: intl] a;//valid int{5] a;//invalid ‘Two dimensional array declaration: Example: int{]D] a int af](J; | Allare valid. int{) (Ja: ] int 00 a; int 1002 int al] int{) Oe int(] a(JQ); | Allare vali int{] alls int(]0) Das int{]Q) all; int els int (Malls Which of the following declarations are valid? 1) int{] 21,b1;//a-1,b-1valid) 2) int[] a2{],b2;//a-2,b-1(valid) 3) int{] (183,b3;//a-2,b-2(valid) 4) int{] a,[]b;//C.E:
expected(invalid) ‘* if we want to specify the dimension before the variable that rule is applicable only for the 1" variable. Second variable onwards we can't apply in the same declaration. BExample: int{] Ua,{)b; inva Array construction: Every array in java is an object hence we can create by using new operator. Example: int{] a=new int[3]; Diagram: ‘© For every array type corresponding classes are available but these classes are part of java language and not available to the programmer level. Array Type corresponding class name int{] Ul int{IO {tl double[] [0 Rule © At the time of array creation compulsory we should specify the size otherwise we will get compile time error. Example: int{) int{) Rule 2: ‘Its legal to have an array with size zero in java, Example: int{] a=new int{O]; System.out.printin(a.length);//0 Rule © If we are taking array size with -ve int value then we will get runtime exception saying NegativeArraySizeException Example: int[] a=new int[-3];//R.E:NegativerraySizeException Rule ‘© The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any other type we will get compile time error. Example: int{] a=new int{‘a'];//(valid) iC.E:array dimension missing 14byte 0; int[] a=new int[b];//(valid) short s=20; int[] a=new int[s];//(valid) int[] a=new int[101];//C.€:possible loss of precision//(invalid) int{] a=new int(10.5];//C.E:possible loss of precision//(invalid) Rule 5: ©The maximum allowed array size in java is maximum value of int size [2147483647]. Example: int[] al=new int[2147483647]; (valid) int[] 2=new int[2147483648];//C.E:integer number too large: 2147483648( invalid) ‘Two dimensional array creation: * In java multidimensional arrays are implemented as array of arrays approach but not matrix form. + The main advantage of this approach is to improve memory utilization. Example 1: int{lt) ew int{2){); yew int[3]; yew int[2]; Diagram: memory representation | Example int{]00) a=new int{2]010; a{0]=new int(3]); a{0][0]=new int[1]; al0]{2}=new int{2]; al0]{2}=new int(3]; jew int(2][2]; 15‘memory representation ala] Which of the following declarations are valid? 1) int{] a=new int[]//C.E: array dimension missing(invalid) 2) int{]{] a=new int{3][4];(valid) 3) int{)[] a=new int[3)[];(valid) 4) int{][] a=new int{][4];//C.E:]' expected{invalid) 5) int{J[J[] a=new int{3](4](5];(valid) 6) _int{J[J[] a=new int(3]{4]{);(valid) 7) int{J[J{] a=new int{3){][5};//C.E:'] expected{invalid) Array initialization: Whenever we are creating an array every element is initialized with default value automatically. Example 1: int{] a=new int(3); System.out.printin(a);//[1@3e25a5 System.out.printin(a[0]);//0 Diagram: a o jo jo Note: Whenever we are trying to print any object reference internally toString() method will be executed which is implemented by default to return the following. classname @hexadecimalstringrepresentationofhashcode. Example 2: —— int{][] asnew int[2][3]; base size System.out.printin(a);//[[1@3e25a5 System.out.printin(a[0});//[1@19821F System.out.printin(a[0}[0]};//0 Diagram 16memory representation af ao] cf ala) Example int{]{] 2=new int(2]1); System.out.printin(a);//[[I@3e25a5 System.out.printin(a[0});//null System. out printin(a[0][0]);//R.E:NullPointerException rll ‘© Once we created an array all its elements by default initialized with default values. if we are not satisfied with those default values then we can replays with our customized values Example: int{] a=new int[4]; a[-4]=60;//R.E:ArrayindexOutOfBoundsException: -4 Diagram: a-€310[620]930|040) Note: if we are trying to access array element with out of range index we will get Runtime Exception saying ArrayindexOutOfBoundsException, jon of an array ‘* We can perform declaration construction and initialization of an array in a single line. Example: He Ii int] a={20,20,30}, 7char[] ch=f'a'/e,7,'0",'U'};(valid) String[] s={"balayya","venki","nag","chiru"};(valid) * We can extend this short cut even for multi dimensional arrays also. Example: int{J{] 2={{10,20,30},{40,50}};> Diagram: 10 [2030] [40 | 50) Example: int{]{J1] @=({{10,20,30},{40,50}},{{60},{70,80},{80,100,110})}; Diagram: coc Gobo int{]1]1] 2=({(20,20,30},(40,50}},{{60),{70,80},(90,100,110}}}; System.out.printin(a[0][1][1]);//50(valid) System.out.printin(a[1}[0][2]);//R.E:ArrayindexOutOfBoundsException: 2(invalid) System.out.printin(a[1][2][1]);//100(valid) System.out.printin(a[1][2][2]);//110(valid) System.out.printin(a[2}[1}[0]);//R.E:ArrayindexOutOfBoundsException: 2(invalid) System.out.printin(a[1][1][1]);//80(valid) ‘* If we want to use this short cut compulsory we should perform declaration, construction and initialization in a single line, If we are trying to divide into multiple lines then we will get compile time error. Example: intl] {00,20,30} int) x: new int{3]s x=(10,20,30}; CEillegal start of expression Jength Vs length length: 1) tis the final variable applicable only for arrays. 2) Itrepresents the size of the array. Example: 18int[] x=new int[3); System.out.printin(x.length());//C.E: cannot find symbol System.out.printin(x.length);//3 length() method: 1) It isa final method applicable for String objects. 2) Itrreturns the no of characters present in the String. Example: String s="bhaskar"; System.out.printin(s.length);//C.E:cannot find symbol System.out.printin(s.length());//7 ‘© In multidimensional arrays length variable represents only base size but not total size. Example: intl w int{6][3]; System.out.printin(a.length);//6 System.out.printin(a[O].length);//3 Diagram oo ‘© length variable applicable only for arrays where as length(Jmethod is applicable for String objects. Anonymous Arrays: ‘© Sometimes we can create an array without name such type of nameless arrays are called anonymous arrays. ‘© The main objective of anonymous arrays i © We can create anonymous array as follows. new int{]{10,20,30,40};(valid) new int{]{]{{10,20},{30,40}};(valid) ‘* At the time of anonymous array creation we can’t specify the size otherwise we will get compile time error. Example: new int[3]{10,20,30,40};//C.t new int{]{10,20,30,40};(valid) ‘© Based on our programming requirement we can give the name for anonymous array then itis no longer anonymous. Example: int{] a=new int(}{10,20,30,40};(valid) ‘just for instant use”. "f expected invalid) 19Example: class Test { public static void main(String[] args) { System.out.printin(sum(new int[}{10,20,30,40}));//100 t public static int sum(int[] x) { int total=( for(int x1:x) { } return total; } Array element assignments: Case 1: In the case of primitive array as array element any type is allowed which can be promoted to declared type. Example 1: For the int type arrays the allowed array element types are byte, short, char int. ew int{10]; ‘/I{valid) a[2]=b;//(valid) short s=20; a[4]=101;//C.E:possible loss of precision Example 2: For float type arrays the allowed element types are byte, short, char, int, long, float. Case 2: In the case of Object type arrays as array elements we can provide either declared type objects or its child class objects. Example 1: Object[] a=new Object[10]; a[0]=new Integer(10);//(valid) ew Object();//(valid) 'ew String("bhaskar");//(valid) 20Number[] n=new Number{10]; }ew Integer(10);//(valid) 1ew Double(10.5);//(valid) Object Number BS LF \ew String("bhaskar");//C.E:incompatible types//(invalid) D Case 3: In the case of interface type arrays as array elements we can provide its implemented class objects. Example: Runnable[] renew Runnable[10); r[0]=new Thread(); r[1]snew String("bhaskar");//C.E: incompatible types Array Type Allowed Element Type 1) Primitive arrays. 1) Any type which can be promoted to declared type. 2) Object type arrays. 2) Either declared type or its child class objects. 3)_Interface type arrays. 3)_Its implemented class objects. 4) Abstract class type arrays. 4)_Its child class objects are allowed. ‘Array variable assignments: Case 1: ‘* Element level promotions are not applicable at array level. * A char value can be promoted to int type but char array cannot be promoted to int array. Example: int(] int{] b int[] c=ch;//C.E:incompatible types(invalid) Which of the following promotions are val 211)char —— int (valid) 2)char[] ——intf] invalid) 3)int ong (valid) 4)int{] ——ongl]{invalid) 5)double- float (invalid) 6}double[] —float[] invalid) ‘7)String—— Object (valid) 8)stringl] Object] (valid) Note: In the case of object type arrays child type array can be assign to parent type array variable. Example: String(] s Object{] Case 2: Whenever we are assigning one array to another array internal elements won't be copy just reference variables will be reassigned hence sizes are not important but types must be matched Example: int[] a={10,20,30,40,50,60,70}; 10]20]30]40]50]60 [70 int 20] s0| Case 3: Whenever we are assigning one array to another array dimensions must be matched that is in the place of one dimensional array we should provide the same type only otherwise we will get compile time error. Example: int{]{] 2=new int(3]1]; a[0]=new int[4][5];//C.E:incompatible types(invalid) //C.E:incompatible types(invalid) yew int[4];//(valid) Note: Whenever we are performing array assignments the types and dimensions must be matched but sizes are not important. Example 1: 2inti] @=new int(3](2; al0]=new int(3]; aft}snew intla]; a=new int{4][3); coooooco Total how many objects created? Ans: 11 How many objects eligible for GC: 6 Example class Test { public static void main(String] args) { String(] argh=("A" args=arah; System.out.printin(args.length);//2 forfint res.lengthii++) { System.out.printin(argstil); } t } Qutput: java Test xy R.E: ArrayindexOutOfBoundsxception: 2 Java Test x 23RE: ArrayindexOutOfBoundsException: 2 java Test R.E: ArrayindexOutOfBoundsException: 2 Note: Replace with icargs.length, Example class Test { public static void main(String] args) { String{] argh=("A","t areszargh; System.out.printin(args.length);//2 for(int i=O;icargs.length;i++) { System.out.printin(argslil]: Output: ers Types of Variables ‘+ Based the type of value represented by the variable all variables are divided into 2 types. They are: 1) Primitive variables 2), Reference variables Primitive variables: Primitive variables can be used to represent primitive values, Examples int x=10; Reference variables: Reference variables can be used to refer objects. Example: Student s=new Student(); Diagram: =@) ‘* Based on the purpose and position of declaration all variables are divided into the following 3 types. 1) Instance variables 2) Static variables 3) Local variables 24if the value of a variable is varied from object to object such type of variables are called instance variables. © For every object a separate copy of instance variables will be created. ‘* Instance variables will be created at the time of object creation and destroyed at the time of object destruction hence the scope of instance variables is exactly same as scope of objects. ‘* Instance variables will be stored on the heap as the part of object, ‘© Instance variables should be declared with in the class directly but outside of any method or block or constructor. ‘Instance variables can be accessed directly from Instance area. But cannot be accessed directly from static area. ‘© But by using object reference we can access instance variables from static area Example: class Test { int i=10; public static void main(String[] args) { //System.out.printin(i);//C.£:non-static variable i cannot be referenced from a static context{invalid) Test tenew Test(); System. out.printin(t.i);//10(valid) ‘tmethodOne(); } public void methodOne() { System.out printin(i)://10(valid) ‘© For the instance variables it is not required to perform initialization JVM will always provide default values. Example: class Test { boolean b; public static void main(String[] args) { Test t=new Test(); 25System.out printin(t.b);//false Instance variables also known as object level variables or attributes. Static variables: if the value of a variable is not varied from object to object such type of variables is not recommended to declare as instance variables. We have to declare such type of variables at class level by using static modifier. In the case of instance variables for every object @ separate copy will be created but in the case of static variables for entire class only one copy will be created and shared by every object of that class. Static variables will be crated at the time of class loading and destroyed at the time of class unloading hence the scope of the static variable is exactly same as the scope of the «class file. Static variables will be stored in method area, Static variables should be declared with in the class directly but outside of any method or block or constructor. Static variables can be accessed from both instance and static areas directly. We can access static variables either by class name or by object reference but usage of class name is recommended. But within the same class it is not required to use class name we can access directly. 1) Start JVM. 2) Create and start Main Thread by JVM. 3) Locate(find) Test.class by main Thread. 4) Load Test.class by main Thread. 5) Execution of main() method. 6) Unload Test.class 7) Terminate main Thread, 8) shutdown JVM. Example: class Test { static int i=10; public static void main(String{] args) { Test t=new Test(); System.outprintin(t.i);//10 System.out.printin(Test.i);//10 System.out.printin();//10 26t ‘* For the static variables it is not required to perform initialization explicitly, JVM will always provide default values. Example: class Test { static String s; public static void main(String[] args) { System.out.printin(s);//null } } Example: class Test { int x=10; static int y=20; public static void main(String{] args) { Test tl=new Testi); tLx=888; tLy=999; Test t2=new Testi); ‘System.out.printin(t2.x#"=--"+t2.y);//10-—-999 } } Diagram: SE) ED © Static variables also known as class level variables or fields. Local variables: © Some time to meet temporary requirements of the programmer we can declare variables inside a method or block or constructors such type of variables are called local variables or automatic variables or temporary variables or stack variables. 27‘© The local variables will be created as part of the block execution in which it is declared and destroyed once that block execution completes. Hence the scope of the local variables is exactly same as scope of the block in which we declared. Example class Test { public static void main(String[] args) { int iO; forlint j=0;j<3++) { iH]; } System.out printin(is"—"4)}; } } Example class Test { public static void main(String{] args) { try { int isinteger.parseint("ten"); } catch(NullPointerException e) { System.out.printin(); } } } ‘© The local variables will be stored on the stack 28‘© For the local variables JVM won't provide any default values compulsory we should perform initialization explicitly before using that variable. Example: dass Tost css Test { Kk publi statie void main(stringt} args) | public static void main(strintl args) © ins © mex ‘System.outprintin("hello";//hello] System. outprntin(x}://C variable x might not have been initialized a L? Example: class Test, { public static void main(String{] args) { int x; iflargs.length>o) { x=10; } System.out printin(x);//C.E:variable x might not have been initialized } } Example: class Test { public static void main(String{] args) { int x; iflargs.length>o) { } else { ¥=20; } System.outprintin(x); } 29} Output: java Test x 10 java Test xy 10 java Test 20 It is never recommended to perform initialization for the local variables inside logical blocks because there is no guarantee of executing that block always at runtime. ‘* It is highly recommended to perform initialization for the local variables at the time of declaration at least with default values, Note: The only applicable modifier for local variables is final. If we are using any other modifier we will get compile time error. Exampl class Test { public static void main(String[] args) { public int x=10; private int x=10; protected int x=10; legal start of expression static int x=10; volatile int x=10; transient int x=10; final int x=10;//(valid) } } Conclusion 1) For the static and instance variables it is not required to perform initialization explicitly JVM will provide default values. But for the local variables JVM won't provide any default values compulsory we should perform initialization explicitly before using that variable. 2) For every object a separate copy of instance variable will be created whereas for entire class a single copy of static variable will be created. For every Thread a separate copy of local variable will be created. 303) Instance and static variables can be accessed by multiple Threads simultaneously and hence these are not Thread safe but local variables can be accessed by only one Thread ata time and hence local variables are Thread safe. UN initialized arrays Example: class Test { intl] a; public static void main(String{] args) { Test ti=new Test(); system.out printin(t1.2);//null System.out printin(t1.a[0]);//R-E:NullPointerException t Instance level: Example int{] a; System. out.printin(obj.a);//null System. out.printin(obj.a[0]);//R.E:NullPointerException Example 2: int{] a=new int[3]; System.out.printin(obj.a);//[1@3e25a5 System.out.printin(obj.a[0]};//0 Static level: Example 1: static int[] 3; System.out.printin(a);//null ‘System.out.printin(a[0});//R.E:NullPointerException Example, static int[] a=new int(3]; system.out.printin(a);//[1@3e25a5, System.out.printin(a[0});//0 Local level; Example 1: intl] a: System.out.printin(a); ye variable a might not have been initialized (al System.out.printin(a[0}); 31Example 2: int[] a=new int[3]; System.out.printin(a);//[1@3e25a5 System.out.printin(a[0});//0 © Once we created an array every element is always initialized with default values irrespective of whether it is static or instance or local array. \Var- arg methods (variable no of argument methods) (1.5 ‘© Until 1.4v we can’t declared a method with variable no. Of arguments. If there is a change in no of arguments compulsory we have to define a new method. This approach increases length of the code and reduces readability. But from 1.5 version onwards we can declare a method with variable no. Of arguments such type of methods are called var-arg methods. © We can declare a var-arg method as follows. methodOne(int... x) LL cttipse ‘© We can call or invoke this method by passing any no. Of int values including zero number. Example: class Test { public static void methodOne(int... x) { System.out printin("\var-arg method"); } public static void main(String[] args) { methodOne(); methodOne(10); methodOne(10,20,30); } } Output: var-arg method var-arg method var-arg method ‘* Internally var-arg parameter implemented by using single dimensional array hence within the var-arg method we can different arguments by using index. Example: 32class Test { public static void sum(int... x) { int total=0; for(int i=O;i
methodOne(int... i) |(valid) Example: class Test { public static void main(String... args) { System.out.printin("var-arg main method');//var-arg main method } t Case 2: Wherever var-arg parameter present we can’t replace with single dimensional array. |methodOne(int... i —>methodOne(int{] i) Example: class Test { public static void methodOne(int[).. x) { for(int{] a:x) { System.out.printin(a[0}); } } public static void main(String[] args) { int{] 1=(10,20,30}; 35int[] m={40,50}; methodOne(|,m); + Output: 10 40 Analysis: methodOne(int... x) methodOne(10,20); ‘methodOne(int[]... x) | {] !={10,20,30}; * [] m={40,50}; ‘methodOne(I,m}; I Main Method © Whether the class contains main() method or not and whether it is properly declared or not these checking’s are not responsibilities of the compiler, at runtime JVM is responsible for this. if jvm unable to find the required main() method then we will get runtime exception saying NoSuchMethodError: main. Example: class Test t Output: Javac Test java Java Test R.E: NoSuchMethodError: main * JVM always searches for the main() method with the following signature. able static main(String] args); ' L Tannin) ins naod wont Econ from any where} [object also jvm | return anything to jvm] [arguments has to call hi Imethod, ‘* If we are performing any changes to the above signature then the code won't run and will get Runtime exception saying NoSuchMethodError. Anyway the following changes are acceptable to main() method. 361) The order of modifiers is not important that is instead of public static we can take static public. 2) We can declare string[] in any acceptable form 1) String(] args 2) String [Jares 3) String args{] 3) Instead of args we can use any valid java identifier, 4) We can replace string[] with var-arg parameter. Example: main(String... args) 5) main() method can be declared with the following modifiers. ‘© final, synchronized, strictfp. Which of the following main() method declarations are valid? 1) public static void main(String args){}(invalid) 2) public synchronized final strictfp void main(String[] args){} (invalid) 3) public static void Main(String... args){} (invalid) 4) public static int main(String[] args){}//int return type we can't take//(invalid) 5) public static synchronized final strictfp void main(String... args){}(valid) In which of the above cases we will get compile time error? ‘+ No case, in all the cases we will get runtime exception © Overloading of the main() method is possible but JVM always calls string[] argument main() method only. Example: class Test { public static void main(String{] args) { System. out.printin("String[] array main method") overloaded methods } public static void main(int[] args) { System.out.printin("int[] array main method"); } Output String[] array main method ‘* The other overloaded method we have to call explicitly then only it will be executed, 37‘© Inheritance concept is applicable for static methods including main() method hence while executing child class if the child class doesn’t contain main{) method then the parent class main() method will be executed. Example class Parent { public static void main(String[] args) { System.out.printin("parent main"); Parent.java } } class Child extends Parent t Analysis: javac Parent.java Child.cass class Parent { public static void main(String[] args) { System.out.printin("parent main"); } } class Child extends Parent Parent,java { public static void main(String{] args) { System.out.printin("Child main"); } } Analysis: 38javac Parent java Parent.class Child.class java Parent arent main java Child Child main ‘* It seems to be overriding concept is applicable for static methods but it is not overriding it is method hiding. Command line arguments: ‘The arguments which are passing from command prompt are called command line arguments. The main objective of command line arguments are we can customize the behavior of the main() method. javaTest 10 20 30 L res{0] ares{t] args{2] args.length=—>3 Example 1: class Test { public static void main(String{] args) { for(int i=0;i<=args.length;i++) { System.out.printin(argstil}: } } t Output: java Test xyz ArraylndexOutOfBoundsException: 3 Example 2: Replace i<=args.length with icargs.length then it will run successfully Within the main() method command line arguments are available in the form of String hence “#” operator acts as string concatenation but not arithmetic addition. Example: class Test 39public static void main(String{] args) { System.out.printin(args[O]+args[1]); + Outpu E:\SCIP>javac Test.java E:\SCuP>java Test 10 20 1020 ‘* Space is the separator between 2 command line arguments and if our command line argument itself contains space then we should enclose with in double quotes. Example: class Test { public static void main(String[] args) { System.out.printin(args[0)); ‘\SCJP>javac Test.java E:\SCIP>java Test "vijaya bhaskar" Vijaya bhaskar Java coding standards * Itis highly recommended to follow coding standards. ‘© Whenever we are writing any component the name of the component should reflect the purpose or functionality Example: class, package com.durgasoft.scjpdemo; { class Cale public int methodOne(int x,int y)] { { public static int addlint number1, int number2) return x+y; 1 } return number1+number2; ) ameorpet standards } } Hitech-city standards Coding standards for classe: 40Usually class names are nouns. ‘© Should starts with uppercase letter and if it contains multiple words every inner word should starts with upper case letter. Example: string, Customer, Object Student stringoutfer | —>nouns Coding standards for interface ‘* Usually interface names are adjectives. ‘* Should starts with upper case letter and if it contains multiple words every inner word should starts with upper case letter. Example: 1) Serializable 2) Runnable | adjectives 3) Cloneable Coding standards for methods: ‘* Usually method names are either verbs or verb noun combination. ‘© Should starts with lowercase character and if it contains multiple words every inner Word should starts with upper case letter. Example: nnd A getName() ) steer) | ce ot wor setslany) jverbnoun iy | nouns © Usually variable names are nouns, ‘© Should starts with lowercase alphabet symbol and if it contains multiple words every inner word should starts with upper case character. Example: length name salary nouns age mobileNumber Coding standards for constant: © Usually constants are nouns. ‘* Should contain only uppercase characters and if it contains multiple words then these Words are separated with underscore symbol. 41‘* Usually we can declare constants by using public static final mot Example: MAX_VALUE| nouns MIN_VALUE Java bean coding standards: * A java bean is a simple java class with private properties and public getter and setter methods. iers. Example: class StudentBean, { [class name ends with bean is not lofficia convention| Lfirom sun. _] Private String name; Public void setName(String name) { this.name=name; } public String getName() t return name; } } Syntax for setter method: 1) Method name should be prefixed with set. 2) It should be public. 3) Return type should be void. 4) Compulsory it should take some argument. Syntax for getter method: 1) The method name should be prefixed with get. 2) It should be public. 3) Return type should not be void 4) itis always no argument method. Note: For the boolean properties the getter method can be prefixed with either get or is. Example: 42private boolean empty; _ | private boolean empty; public boolean getEmpty() | public boolean ismpty() { { return empty; return empty; + y (valid) (valid) both are valid. ‘* Method name should be prefixed with add, 1) public void addyActiontistener(MyActiontistener |)(valid) 2) public void registerMyActionListener(MyActionListener |)(invalid) 3) public void addMyActionListener(ActionListener |)(invalid) To unregister a listener: ‘© The method name should be prefixed with remove. 1) public void removeMyActionListener(MyActionListener |)(valid) 2). puble void unregisterMyActionListener(MyActionListener |){invalid) 3) public void removeMyActionListener(ActionListener I)(invalid) 4) public void delete MyActionListener(MyActionListener I)(invalid) 43Declaration and Access Modifi 1) Java source file structure 2) Class modifiers 3) Member modifiers 4) interfaces, Java source file structure: ‘© A java program can contain any no. Of classes but at mot one class can be declared as public. "If there is a public class the name of the program and name of the public class must be matched otherwise we will get compile time error”. ‘* If there is no public class then any name we gives for java source file. public <—felass 8 public<—|class ¢ Case! ‘© If there is no public class then we can use any name for java source file there are no restrictions. Example: Ajava B.java Clava 44Bhaskar java ‘If class B declared as public then the name of the program should be B.java otherwise we will get compile time error saying “class B is public, should be declared in a file named B java” (ae3: ‘* If both B and C classes are declared as public and name of the file is B,java then we will get compile time error saying “class C is public, should be declared in a file named java”. ‘* itis highly recommended to take only one class for source file and name of the program (file) must be same as class name. This approach understandability of the code. Example: class A { public static void main(String args{]){ System.out.printin("A class main method is executed"); } } class B { public static void main(String args[]){ System.out printin("B class main method is executed”); } } class C { public static void main(String args[]){ System.out.printin("C class main method is executed"); improves readability and 45javac_Bhaskar.java Ajava Bijava Cjava D.java D:\lava>java A A class main method is executed D:\lava>java 8 B class main method is executed D:\lava>java C C class main method is executed D:\lava>java D Exception in thread "main" java.lang.NoSuchMethodError: main D:\lava>java Bhaskar Exception in thread "main" java.lang.NoClassDefFoundError: Shaskar ‘* We can compile a java program but not java class in that program for every class one dot class file will be created, © We can run a java class but not java source file whenever we are trying to run a class the corresponding class main method will be executed. ‘* If the class won't contain main method then we will get runtime exception saying “NoSuchMethodError: main” ‘© If we are trying to execute a java class and if the corresponding .class file is not available then we will get runtime execution saying “NoClassDefFoundError: Bhaskar”. Import statement class Test{ public static void main(String args{]){ ArrayList Isnew Arraylist(); } } Output: Compile time error. D:\lava>javac Test.java Test.java:3: cannot find symbol symbol = class ArrayList location ArrayList Isnew ArrayList(); Test.java:3: cannot find symbol symbol = class ArrayList location: class Test : class Test 46ArrayList I=new ArrayList; ‘© We can resolve this problem by using fully qualified name “java.util ArrayList Ienew java.util Arraylist();”. But problem with using fully qualified name every time is it increases length of the code and reduces readability ‘* We can resolve this problem by using import statements Example: import java.util. ArrayList; class Test{ public static void main(String args{]){ ArrayList I=new ArrayList(); } } Output Di\lava>javac Test java * Hence whenever we are using import statement it is not require to use fully qualified names we can use short names directly. This approach decreases length of the code and improves readability. Case 1: Types of Import Statements: ‘There are 2 types of import statements. 1) Explicit class import 2) Implicit class import, Explicit class impor Example: Import java.util ArrayList ‘+ This type of import is highly recommended to use because it improves readability of the code. Best suitable for Hi-Tech city where readability is important. Implicit class import: Example: import java.util"; ‘+ Itis never recommended to use because it reduces readability of the code. * Bet suitable for Ameerpet where typing is important. Case: Which of the following import statements are valid? import java.util; x import java.util ArrayList. import java.util"; import java.util Arraylist; \/ '* consider the following code. 47class MyArrayList extends java.util. ArrayList, { } The code compiles fine even though we are not using import statements because we used fully qualified name. Whenever we are using fully qualified name it is not required to use import statement. Similarly whenever we are using import statements it is not require to use fully qualified name. Cased: Example: Import java.util.*; import java.sql.*; class Test { public static void main(String args[]) { Date d=new Date(); n Output: Compile time error. D:\lava>javac Test.java Test java:7: reference to Date is ambiguous, both class java.sql.Date in java.sql and class java.util.Date in java.util match Date d=new Date(); ‘Note: Even in the List case also we may get the same ambiguity problem because it is available in both UTIL and AWT packages. Gases: ‘* While resolving class names compiler will always gives the importance in the following order. 1) Explicit class import 2) Classes present in current working directory. 3) Implicit class import. Example: import java.util.Date; import java.sal.*; class Test { public static void main(String args{]){ 43Date d=new Date(); y ‘* The code compiles fine and in this case util package Date will be considered. ‘Whenever we are importing a package all classes and interfaces present in that package are by default available but not sub package classes. To use pattern class in our program directly which import statement is required? Limport java.*; 2.import java.util."; >< 3.import java.util.regex.*;\/ 4.import java.util.regex.Pattern; \/ ‘¢ In any java program the following 2 packages are not require to import because these are available by default to every java program. 1. javalang package 2. default package(current working directory) ‘+ “Import statement is totally compile time concept” if more no of imports are there then more will be the compile time but there is “no change in execution time” Difference between C language #include and java language import. ‘© In the case of C language #include all the header files will be loaded at the time of include statement hence it follows static loading ‘© But in java import statement no “class” will be loaded at the time of import statements in the next lines of the code whenever we are using a particular class then only corresponding “.class” file will be loaded. Hence it follows “dynamic loading” or “load- on-demand” or “load-on-fly”. Static import: © This concept introduced in 1.5 versions. According to sun static import improves readability of the code but according to worldwide programming exports (like us) static 43imports creates confusion and reduces readability of the code. Hence if there is no specific requirement never recommended to use a static import, 15 versions new features 1) For-Each 2) Var-are 3) Queue 4) Generics 5) Auto boxing and Auto unboxing 6) Co-varient return types 7) Annotations 8) Enum 9) Static import 10) String builder ‘© Usually we can access static members by using class name but whenever we are using static import it is not require to use class name we can access directly. Without static impor class Test { public static void main(String args[]){ ‘System.out.printin(Math.sqrt(4)); System. out printin(Math.max(10,20)); System.out.printin(Math.random()); y Output: D:\lava>javac Test java D:\lava>java Test 20 20 0.841306154315576 ith static import: import static java.lang.Math.sqrt; import static java.lang.Math.*; class Test { public static void main(String args{}){ System.out.printin(sqrt(4)); System. out.printin(max(10,20)); System.out.printin(random()); 50tt Output: D:\Java>javac Test java D:\Java>java Test 20 20 0.4302853847363891 Explain about System.out.printin statement? Example 1 and example a) 2) Iclass Test import java.io. K lass System |static String name="bhaskar"} |{ static PrintStream out, Test.ngme.length(); System.out.printin() (isa dass]|static variable] lof type string |presentin loresent in | |string class jpresent in Jof fype PrintStream java.tang pkg. [prdsent iri cn itis a dass se variable System clas is a method presen eam class, Example import static java.lang.System.out; class Test { public static void main(String args{]){ out printin("hello"); out printin("hi"); y Output: D:\lava>javac Test java D:\lava>java Test hello hi Example 4: import static java.lang.Integer.*; 51import static java.lang.Byte.*; class Test { public static void main(String args{}){ System.out. printin(MAX_VALUE); y Output: Compile time error. D:\lava>javac Test.java Test.java:6: reference to MAX VALUE is ambiguous, both variable MAX VALUE in java.lang.Integer and variable MAX_VALUE in java.lang.Byte match System.out.printin(MAX_VALUE); Note: Two packages contain a class or interface with the same is very rare hence ambiguity problem is very rare in normal import. ‘© But 2 classes or interfaces can contain a method or variable with the same name is very common hence ambiguity problem is also very common in static import. + While resolving static members compiler will give the precedence in the following order. 1. Current class static members 2. Explicit static import 3. implict static import, java.tang. nteger.MAX_VALUE;——> line2 import static java.lang.Byte.*; class Test { //static int MAX_VALUE=999;—line1 public static void main(String args[})throws Exception System.out.printIn(MAX_VALUE); } } ‘* If we comet line one then we will get Integer class MAX_VALUE 2147483647, ‘* If we comet lines one and two then Byte class MAX_VALUE will be considered 127. Which of the following import statements are valid? ‘Limport java.lang.Math.*; x 2.import static java.lang.Math.*; \~ 3.import java.lang.Math;\~ 4.import static java.tang.Math; x S.import static java.tang.Math.sqrt.*; x 6.import java.lang.Math.sart; x 7.import static java.lang.Math.sqrt();x. 8.import static java.lang.Math.sqrti \~ 52Math, ‘normal import starts with—| uti Math sare: static import starts with—} Ls mathe: ‘© Usage of static import reduces readability and creates confusion hence if there is no specific requirement never recommended to use static import. What is the difference between general import and static import? ‘© We can use normal imports to import classes and interfaces of a package. whenever we are using normal import we can access class and interfaces directly by their short name it is not require to use fully qualified names, ‘* We can use static import to import static members of a particular class. whenever we are using static import it is not require to use class name we can access static members directly. Package statement: ‘It is an encapsulation mechanism to group related classes and interfaces into a single module, The main objectives of packages are: ‘© Toresolve name confects ‘* To improve modularity of the application. © To provide security. ‘© There is one universally accepted naming conversion for packages that is to use internet client internet module submodule class domainname name How to compile package program: Example: package com.durgajobs.itjobs; class HydJobs { public static void main(String args[]){ System.out printin(’ domain name in reverse. Example: ackage dem 53* Javac Hydlobs java generated class file will be placed in current working directory. wd [ Hydlobs.class © Javac-d. Hydlobs.java ‘+ -dmeans destination to place generated class files “.” means current working directory. ‘© Generated class file will be placed into corresponding package structure. ond durgajobs P Hitiobs F pyatobscass © If the specified package structure is not already available then this command itself will create the required package structure. ‘* Asthe destination we can use any valid directory. If the specified destination is not available then we will get compile time error. Example: D’\lava>javac -d c: Hydlobs,java om P curgsobs Fitts [Ftvdiobs.class ‘If the specified destination is not available then we will get compile time error. Example: D:\lavapjavac -d 2: HydJobs java ‘© If2:is not available then we will get compile time error. How to execute package program: D:\lava>java com.durgajobs.itjobs.Hydlobs ‘© At the time of execution compulsory we should provide fully qualified name. Conclusion 1: 54‘© In any java program there should be at most one package statement that is if we are taking more than one package statement we will get compile time error. Example: package pack1; package pack2; class A { } Output: Compile time error. D:\lava>javac A.java ‘A.javai2: class, interface, or enum expected package pack2; Conclusion 2: In any java program the 1* non cement statement should be package statement [if it is available] otherwise we will get compile time error. Example: import java.util.*; package pack1; class A { } Output: Compile time error. D:\lavapjavac A.java A java:2: class, interface, or enum expected package pack1; Java source file structure: ‘At most one] package statement orders any number is allowe import statement important any number- class/interface/enum declarations ‘* Allthe following are valid java programs. [package pack: import java.util."[package packi; [class Test import java.util] (} Testjava_ —_Testjava Testjava Vv Vv v Note: An empty source file is a valid java program Class Modifiers 55
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6125)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (932)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8214)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
3.5/5 (2061)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2619)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Yes Please
From Everand
Yes Please
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel