├── java class_durgasoft.tar.gz ├── java class_durgasoft ├── Assertions ├── Command line arguments ├── Constructor ├── Coupling-and-typecasting ├── Declaration and accessmodifiers ├── Exception Handling ├── Flow-control ├── Generics ├── Generics~ ├── Inner classes ├── Interfaces ├── Singleton class ├── Some IMP Points ├── String, StringBuffer, StringBuilder ├── Types of variables ├── Wrapper classes ├── arrays in java ├── chapter names ├── chapter names~ ├── collection_framework ├── control-flow ├── enum ├── garbage collection ├── has - a relationship & overriding ├── java Codding Standards ├── java_lang package ├── language fundamentals - part 1 ├── language fundamentals- datatypes ├── litrals ├── main method ├── oop's concepts - 1 ├── operators&assignments ├── overriding ├── questions ├── serialization ├── serialization~ ├── tests │ ├── ans │ └── ans1 └── var-args ├── java_io └── java_io~ /java class_durgasoft.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbdaliDahir/java-java_notes_dugrasoft/a2fb4cdbbed91d3520a2964e0d8cd39ebf529e29/java class_durgasoft.tar.gz -------------------------------------------------------------------------------- /java class_durgasoft/Assertions: -------------------------------------------------------------------------------- 1 | Assertions 2 | 3 | 1. Introduction----------> IMP 4 | 2. use assertion as keyword and identifiers. 5 | 3. Types of assert statement 6 | 4. Various possible run-time flags. 7 | 5. Appropriate and inappropriate use of Assertions 8 | 6. Assertion Error 9 | 10 | ________________________________________________________________________ 11 | 12 | Introduction 13 | _________________ 14 | 15 | Very common way of debugging is usage of sops statement but the problem with sops is after fixing the bug compulsory we have to delete sop statements otherwise these sop's will be executed at run-time for every request, which creates performance problems and disturbs server log. 16 | 17 | To overcome this problem sun people introduced assertions concept in 1.4 version of java. 18 | 19 | The main advantage of assertions when compared with sops is after fixing the bug we are not required to remove assert statements because then won't be executed by default at run-time based on our requirement we can enable and disable assertions and by default assertions are disabled. 20 | 21 | hence the main objective of assertions is to perform debugging. 22 | 23 | Usually we can perform debugging in development and test environment but not in production environment hence Assertions concept applicable for development and test environments but not for production. 24 | 25 | ____________________________________ 26 | Assert as keyword and identifier 27 | ____________________________________ 28 | 29 | Assert keyword introduced in 1.4 version hence from 1.4 version onwards we can't use assert as identifier. Otherwise we will get compile time error. 30 | 31 | e.g 32 | 33 | class Test{ 34 | public static void main(String[] args){ 35 | int assert = 10; 36 | System.out.println(assert); 37 | } 38 | } 39 | 40 | javac Test.java 41 | 42 | CE : as of release 1.4, 'assert' is a keyword, and may not be used as an identifier 43 | (use -source 1.3 or lower to use 'assert' as an identifier) 44 | 45 | javac -source 1.3 Test.java 46 | 47 | code compiles fine but with warning. 48 | 49 | javac -source 1.3 Test.java //valid 50 | 51 | javac -source 1.4 Test.java //invalid 52 | 53 | javac -source 1.5 Test.java //invalid 54 | 55 | Note : 1. if we are using assert as identifier and if we are trying to compile according to old version (1.3 or lower) then the code compiles fine but with warning. 56 | 57 | Note : 2 We can compile a java program according to a particular version by using -source option. 58 | 59 | Types of assert statements. 60 | ___________________________ 61 | 62 | There two types of assert statement 63 | 64 | 1. Simple version 65 | 2. Argument version 66 | 67 | Simple Version 68 | _______________ 69 | 70 | Syntax : assert(b); //b should be boolean type. 71 | 72 | if b is true then our assumption satisfied and hence rest of the program will be executed normally. 73 | 74 | if b is false then our assumption fails i.e some where something goes wrong and hence the program will be terminated abnormally by rising assertion error. Once we got assertion error we will analyze the code and we can fix the problem. 75 | 76 | e.g 77 | 78 | class Test{ 79 | public static void main(String[] args){ 80 | int x = 10; 81 | ;;;;;;;;;;;;;;;;;;;;; 82 | ;;;;;;;;;;;;;;;;;;;;; 83 | assert(x > 10); 84 | 85 | ;;;;;;;;;;;;;;;;;;;;; 86 | ;;;;;;;;;;;;;;;;;;;;; 87 | System.out.println(x); 88 | } 89 | } 90 | 91 | javac Test.java 92 | java Test 93 | output : 94 | 95 | 10 96 | 97 | java -ea Test 98 | 99 | RE : AssertionError : 100 | 101 | Note : by default assert statement won't be executed because assertions are disabled by default. But we can enable assertions by using '-ea' option. 102 | 103 | Argumented Version 104 | __________________ 105 | 106 | we can argument some description with assertion error by using argumented version 107 | 108 | Syntax : 109 | 110 | assert(b):e; // b should be boolean type, e can be any type but mostly String type 111 | 112 | e.g 113 | 114 | class Test{ 115 | public static void main(String[] args){ 116 | int x = 10; 117 | ;;;;;;;;;;;;;;;;;;;;;;;; 118 | assert(x > 10):"Hear x value should be > 10 but it is not"; 119 | ;;;;;;;;;;;;;;;;;;;;;;;; 120 | System.out.println("value of x is" + x); 121 | } 122 | } 123 | 124 | javac Test.java 125 | 126 | java Test 127 | 128 | o/p : 10 129 | 130 | java -ea Test 131 | 132 | RE : AssertionError : Hear x value should be > 10 but it is not. 133 | 134 | Conclusion 1 : 135 | 136 | 137 | assert b : e 138 | 139 | e will be executed if and only if first argument is false i.e if the first argument is true then second argument won't be evaluated/executed. 140 | 141 | e.g 142 | 143 | class Test{ 144 | public static void main(String[] args){ 145 | int x = 10; 146 | assert(x == 10) : ++x 147 | sopln(x); 148 | } 149 | } 150 | 151 | javac Test.java 152 | 153 | java Test 154 | 155 | o/p 156 | 157 | 10 158 | 159 | java -ea Test 160 | 161 | o/p 162 | 163 | 10 164 | 165 | conclusion 2 : 166 | 167 | Syntax : assert b : e 168 | 169 | for the second argument we can take method call but void return type method call is not allowed. Otherwise we will get compile-time error. 170 | 171 | e.g class Test{ 172 | public static void main(String[] args){ 173 | int x = 10; 174 | assert(x > 10):m1; 175 | 176 | sopln(x); 177 | } 178 | 179 | public static int m1(){ 180 | 181 | return 777; 182 | } 183 | } 184 | 185 | javac Test.java 186 | 187 | java Test 188 | 189 | 10 190 | 191 | java -ea Test 192 | 193 | AssertionError : 777 194 | 195 | if m1() method return type is void then we will get compile time error saying 'void' type not allowed here. 196 | 197 | among 2 versions of assertions it is recommended to use argumented version because it provides more information for debugging. 198 | 199 | _________________________________ 200 | Various possible run-time flags 201 | _________________________________ 202 | 203 | 1. -ea or -enableassertions 204 | 205 | To enable assertions in every non-system class (our own classes). 206 | 207 | 2. -da or -disableassertions 208 | 209 | To disable assertions in every non-System class. 210 | 211 | 3. -esa or -enablesystemassertions 212 | 213 | To enable assertions in every system class(pre defined classes) 214 | 215 | 4. -dsa or disablesystemassertions 216 | 217 | To disable assertions in every system class. 218 | 219 | we can use above flags simultaneously then JVM will consider these flags from left to right. 220 | 221 | e.g -ea -esa -ea -dsa -da -esa -ea -dsa Test 222 | 223 | Non system System 224 | ________________________________________ 225 | 226 | true true 227 | true false 228 | false true 229 | true false 230 | 231 | 232 | 233 | at the end assertions will be enabled in every non-system class and disabled in every system class. 234 | 235 | case Study 236 | _______________ 237 | 238 | pack1 239 | |-A class 240 | | 241 | |-B class 242 | | 243 | | 244 | |___pack2 245 | | 246 | |---C class 247 | | 248 | |---D class 249 | | 250 | | 251 | 252 | 1. To enable assertions only in B class 253 | 254 | java -ea:pack1.B 255 | 256 | 2. To enable assertions in both B and D classes 257 | 258 | java -ea:pack1.B -ea:pack1.pack2.D 259 | 260 | 3. To enable assertions in every class of pack1 261 | 262 | java -ea:pack1... 263 | 264 | 4. To enable assertions in every class of pack1 except B class 265 | 266 | java -ea:pack1... -da:pack1.B 267 | 268 | 5. To enable assertions in every class of pack1 except pack2 269 | 270 | java -ea:pack1... -da:pack1.pack2... 271 | 272 | Note : we can enable and disable assertions either class wise or package wise also. 273 | 274 | ___________________________________________________ 275 | Appropriate and inappropriate use of assertions 276 | ___________________________________________________ 277 | 278 | 1. It is always inappropriate to mix programming login with assert statements because there is no guarantee for execution of assert statement always at runtime. 279 | 280 | e.g 281 | 282 | appropriate way in appropriate way 283 | public void Withdraw(double amt){ public void Withdraw(double amt){ 284 | if(amt < 100){ assert(amt > 100): 285 | throw new IllegalRequestException(); packed request 286 | }else{ } 287 | proceed; 288 | } 289 | } 290 | 291 | 2. while performing debugging in our program if there is any place where the control is not allowed to reach i.e is best place to use assertions. 292 | 293 | 294 | e.g 295 | |-----------should be a valid number 296 | switch(x){ 297 | case 1 : sop("jan"); 298 | break; 299 | case 2 : sop("Feb"); 300 | break; 301 | case 3 : sop("Mar"); 302 | break; 303 | . 304 | . 305 | . 306 | case 12 : sop("Dec"); 307 | break; 308 | default : 309 | assert(false);--------------> RE : AssertionError 310 | 311 | } 312 | 313 | 3. It is always in-appropriate for validating public method arguments by using assertions because outside person doesn't aware whether assertions are enabled or disabled in our system. 314 | 315 | 4. It is always appropriate for validating private method arguments by using assertions because local person can aware whether assertions are enabled or disabled in our system. 316 | 317 | 5. It is always inappropriate for validating command line arguments by using assertions because these are arguments to main(), which is public. 318 | 319 | e.g 320 | 321 | class Test{ 322 | int z = 5; 323 | 324 | public void m1(int x){ 325 | assert(x > 10)----->Inappropriate 326 | 327 | switch(x){ 328 | case 5: 329 | sopln(100); 330 | break; 331 | case 8: 332 | sopln(800); 333 | break; 334 | . 335 | . 336 | . 337 | default : 338 | assert(false);--->appropriate 339 | } 340 | } 341 | 342 | private void m1(){ 343 | assert(x < 10);------->appropriate 344 | } 345 | 346 | private void m3(){ 347 | assert(m4());--------------->inappropriate 348 | } 349 | 350 | private boolean m4(){ 351 | z = 6; 352 | return true; 353 | } 354 | } 355 | 356 | Assert as a keyword, assert as a identifier 357 | 358 | class One{ 359 | public static void main(String[] args){ 360 | int assert = 10; 361 | sopln(assert); 362 | } 363 | } 364 | 365 | class Two{ 366 | public static void main(String[] args){ 367 | int x = 10; 368 | assert(x>10); 369 | } 370 | } 371 | 372 | 1. javac -source 1.3 One.java------> compiles fine but with warning 373 | 374 | 2. javac -source 1.4 One.java------> CE : 375 | 376 | 3. javac -source 1.3 Two.java------> CE : 377 | 378 | 4. javac -source 1.4 Two.java------> Compiles fine without warning. 379 | 380 | class Test{ 381 | public static void main(String[] args){ 382 | boolean assertOn = false; 383 | 384 | assert(assertOn):assertOn = true; 385 | 386 | if(assertOn){ 387 | sopln("assertOn"); 388 | } 389 | } 390 | } 391 | 392 | if assertion is not enabled ? 393 | 394 | no o/p 395 | 396 | if assertions are enabled? 397 | 398 | RE : AssertionError. 399 | 400 | 401 | class Test{ 402 | public static void main(String[] args){ 403 | boolean assertOn = true; 404 | 405 | assert(assertOn):assertOn = false; 406 | 407 | if(assertOn){ 408 | sopln("assertOn"); 409 | } 410 | } 411 | } 412 | 413 | if assertion is not enabled ? 414 | 415 | o/p assertOn 416 | 417 | if assertions are enabled? 418 | 419 | o/p assertOn 420 | 421 | ____________________ 422 | AssertionError 423 | ____________________ 424 | 425 | It is the child class of error and hence it is unchecked. 426 | 427 | If assert statement fails (i.e. argument is false) then we will get assertions error. 428 | 429 | even though it is legal to catch assertion error but it's not a good programming practice. 430 | 431 | class Test{ 432 | public static void main(String[] args){ 433 | int x = 10; 434 | 435 | try{ 436 | assert(x>10); 437 | }catch(AssertionError e){ 438 | sopln("It is stupid thing to catch assertionError"); 439 | } 440 | sopln(x); 441 | } 442 | } 443 | 444 | in the case of web applications if we run java program in debug mode then automatically assert statements will be executed. 445 | -------------------------------------------------------------------------------- /java class_durgasoft/Command line arguments: -------------------------------------------------------------------------------- 1 | The arguments which are passing from command prompt are called command line arguments with these command line arguments JVM will create an array and by passing that array as argument jvm will call main method 2 | 3 | e.g 4 | 5 | java Test a b c 6 | 7 | args[0]----->a 8 | args[0]----->b 9 | args[0]----->c 10 | 11 | args.length------>3 12 | 13 | The main objective of command line arguments is we can customize behaviour of the main method. 14 | 15 | e.g 1 16 | 17 | class Test{ 18 | public static void main(String[] args){ 19 | for(int i = 0; i <= args.length; i++){ 20 | sopln(args[i]); 21 | } 22 | } 23 | } 24 | 25 | outptu: 26 | java Test a b c 27 | a b c 28 | RE: AIOOB 29 | 30 | java Test a b 31 | a b 32 | RE : AIOOB 33 | 34 | java Test 35 | 36 | RE : AIOOB 37 | 38 | if we replace <= with < then we won't get any runtime exception 39 | 40 | class Test{ 41 | public static void main(String[] args){ 42 | String[] argh = new String{"x","y","z"}; 43 | for(int i = 0; i < args.length; i++){ 44 | sopln(args[i]); 45 | } 46 | } 47 | } 48 | 49 | outptu: 50 | java Test a b c 51 | x y z 52 | 53 | java Test a b 54 | x y z 55 | 56 | java Test 57 | 58 | x y z 59 | 60 | wthin main method command line arguments are available in String form 61 | 62 | class Test{ 63 | public static void main(String[] args){ 64 | sopln(args[0]+args[1]); 65 | } 66 | } 67 | 68 | output: 69 | java Test 10 20 70 | 71 | o/p : 1020 72 | 73 | usually space itself is the seprator between command line arguments if our command line argument itself contains space then we have to enclose that command line argument within double codes("") 74 | 75 | class Test{ 76 | public static void main(String[] args){ 77 | sopln(args[0]); 78 | } 79 | } 80 | 81 | 82 | output: 83 | 84 | java Test Note book 85 | 86 | o/p Note 87 | 88 | java Test "Note book" 89 | 90 | o/p Note book 91 | -------------------------------------------------------------------------------- /java class_durgasoft/Constructor: -------------------------------------------------------------------------------- 1 | _______________________ 2 | Constructors 3 | _______________________ 4 | 5 | once we creates an object compulsary we should perform initialization then only the object is in a position to respond properly. 6 | whenever we are creating an object some peace of the code will be executed automatically to perform initialization of the object this peace of the code is nothing but constructor. Hence the main purpose of constructor is to perform initialization of an object 7 | 8 | e.g 9 | 10 | class Student{ 11 | String name; 12 | int rollno; 13 | 14 | public Student(String name, int rollno){ 15 | this.name = name; 16 | this.rollno = rollno; 17 | } 18 | 19 | public static void main(String[] args){ 20 | Strudent s1 = new Student("Test123", 20); 21 | Strudent s2 = new Student("xyz456", 30); 22 | } 23 | } 24 | 25 | Note : The main purpose of constructor is to perform initialization of an object but not to create object. 26 | 27 | 28 | Difference between Constructor and instance block. 29 | 30 | The main purpose of constructor is to perform initialization of an object. 31 | But otherthan initialization if we want to perform any activity for every object creation then we should go for instance block (like updating one entry in the database for every object creation or incrementing count value for every object creation etc). 32 | 33 | both constructor and instance block have there won different purposes and replacing one concept with another concept may not work always. 34 | 35 | both constructor and instance block will be executed for every object creation but instance block first followed by constructor. 36 | 37 | 38 | Demo program to print number of objects created for a class. 39 | 40 | class Test{ 41 | static int count = 0; 42 | { 43 | count++; 44 | } 45 | Test(){ 46 | 47 | } 48 | 49 | Test(int i){ 50 | 51 | } 52 | Test(double d){ 53 | 54 | } 55 | public static void main(String[] args){ 56 | Test t1 = new Test(); 57 | Test t2 = new Test(10); 58 | Test t3 = new Test(20.5); 59 | System.out.println("Count " + count); 60 | } 61 | 62 | } 63 | 64 | _________________________________ 65 | Rules of writing constructors: | 66 | _________________________________| 67 | 68 | 1. Name of the class and name of the constructor must be matched. 69 | 2. Return type concept is not applicable for constructor even void also. 70 | 3. By mistake if we are trying to declare return type for the constructor then we won't get any compile-time error because compiler treats it as a method. 71 | 72 | e.g 73 | 74 | class Test{ 75 | void Test(){ 76 | System.out.println("It is method but not constructor"); 77 | } 78 | 79 | public static void main(String[] args){ 80 | Test t = new Test(); 81 | 82 | t.Test(); 83 | } 84 | } 85 | 86 | output : 87 | It is method but not constructor 88 | 89 | hence it is leagle (but stupid) to have a method whose name is exactly same as class name. 90 | 91 | The only applicable modifiers for constructors are public, private, protected, default if we are trying to use any other modifier we will get compile time error. 92 | 93 | class Test{ 94 | static Test(){} //CE: Modifier static not allowed hear. 95 | } 96 | 97 | Compiler is responsible to generate default constructor but not JVM 98 | if we are not writting any constructor then only compiler will generate default constructor i.e. if we are writting atlist one constructor compiler won't generate default constructor hence every class in java can contain constructor it may be default constructor generated by compiler or costumized constructor explicitly provided by compiler but not both symeltuniously. 99 | 100 | 101 | _________________________________ 102 | Protoype of default constructor 103 | _________________________________ 104 | 105 | 1. It is always no-arg constructor 106 | 2. the access modifier of default constructor is exactly same as access modifier of class (this rule is applicable only for public and default) 107 | 3. it contains only one line super(); 108 | ________ 109 | 110 | It is a no-argument call to super class constructor. 111 | 112 | 113 | Programmers code Compiler generated code 114 | __________________________________________________________________________________________________________ 115 | 116 | class Test{ class Test{ 117 | Test(){ 118 | } super(); 119 | } 120 | 121 | ___________________________________________________________________________________________________________ 122 | public class Test{ public class Test{ 123 | public Test(){ 124 | super(); 125 | } 126 | } } 127 | 128 | _____________________________________________________________________________________________________________ 129 | public class Test{ public class Test{ 130 | void Test(){ public Test(){ 131 | } super(); 132 | } } 133 | 134 | void Test(){ 135 | } 136 | } 137 | 138 | ______________________________________________________________________________________________________________ 139 | class Test{ class Test{ 140 | Test(){ Test(){ 141 | super(); 142 | } } 143 | } } 144 | 145 | _______________________________________________________________________________________________________________ 146 | class Test{ class Test{ 147 | Test(){ Test(){ 148 | super(); super(); 149 | } } 150 | } } 151 | 152 | ________________________________________________________________________________________________________________ 153 | class Test{ class Test{ 154 | Test(){ Test(){ 155 | this(10); this(10); 156 | } } 157 | Test(int i){ Test(int i){ 158 | } super(); 159 | } } 160 | } 161 | _________________________________________________________________________________________________________________ 162 | 163 | The first line inside every constructor should be either super or this. 164 | and if we are not writting any thing then compiler will always place super(). 165 | 166 | Case 1: we can use super() or this() only in first line of constructor. If we are trying to take anywhere else we will get compile time error 167 | 168 | e.g 169 | 170 | class Test{ 171 | Test(){ 172 | System.out.println("constructor"); 173 | super(); //CE : call to super must be first statement in constructor 174 | } 175 | } 176 | 177 | case 2 : within the constructor we can take either super or this but not both symuleniously 178 | 179 | e.g 180 | class Test{ 181 | Test(){ 182 | super(); 183 | this(); // CE : call to this must be first statement in constructor 184 | } 185 | } 186 | 187 | case 3 : we can use super() or this() only inside constructor if we are trying to use outside of constructor we will get compile time error 188 | 189 | e.g 190 | class Test{ 191 | public void m1(){ 192 | super(); //CE : call to super must be first statement in constructor 193 | Sopln("Hello"); 194 | } 195 | } 196 | 197 | i.e we can call a constructor directly from another constructor only 198 | 199 | 200 | ********************** we can use only in first line 201 | * super or this * we can use only one but not both symulteniously 202 | ********************** we can use only in constructor 203 | 204 | 205 | super(), this() super, this 206 | __________________________________________________________________________ 207 | 1. These are constructor calls These are keywords 208 | to call super class and current to referrer super class and 209 | class constructors current class instance members 210 | 211 | 2. we can use only in constructors we can use anywhere except static area 212 | as first line 213 | 214 | 3. we can use only once in constructor we can use any number of times. 215 | 216 | e.g 217 | 218 | class Test{ 219 | public static void main(String[] args){ 220 | System.out.println(super.hashCode()); //non static variable super can't be referenced from a static context. 221 | } 222 | } 223 | 224 | ________________________ 225 | Overloaded constructors | 226 | ________________________| 227 | 228 | within a class we can declare multiple constructors and all these constructors having same name but different type of arguments. Hence all these constructors are considered as overloaded constructors. Hence overloading concept applicable for constructors. 229 | 230 | e.g 231 | class Test{ 232 | Test(){ 233 | Test(10); 234 | sopln("noarg"); 235 | } 236 | Test(int i){ 237 | Test(10.5); 238 | sopln("int args"); 239 | } 240 | Test(double d){ 241 | sopln("double args"); 242 | } 243 | 244 | public static void main(String[] args){ 245 | Test t1 = new Test(); 246 | Test t2 = new Test(10); 247 | Test t3 = new Test(10.5); 248 | Test t1 = new Test(10l); 249 | } 250 | } 251 | 252 | output : 253 | 254 | double args 255 | int args 256 | no args 257 | 258 | double args 259 | int args 260 | 261 | double args 262 | 263 | double args 264 | 265 | for constructors inheritance and overridding concepts are not applicable but overloading concept is applicable 266 | 267 | every class in java including abstract class can contains constructor but interface doesn't contain constructor. 268 | 269 | 270 | class Test{ 271 | Test(){ 272 | //valid 273 | } 274 | } 275 | 276 | abstract class Test{ 277 | Test(){ 278 | //valid 279 | } 280 | } 281 | 282 | interface Test{ 283 | Test(){ 284 | //invalid 285 | } 286 | } 287 | 288 | case 1 : 289 | recursive method call is a runtime exception saying stackOverFlowError but in out program if there is a chance of recursive constructor 290 | -------------------- 291 | invocation then the code won't compile and we will get compile time error. 292 | 293 | class Test{ 294 | 295 | public static void m1(){ 296 | m2(); 297 | } 298 | public static void m2(){ 299 | m1(); 300 | } 301 | public static void main(String[] arg){ 302 | m1(); 303 | 304 | System.out.println("Hello"); 305 | } 306 | } 307 | 308 | output : 309 | 310 | CE :StackOverflowError 311 | 312 | class Test{ 313 | 314 | Test(){ 315 | this(10); 316 | } 317 | Test(int i){ 318 | this(); 319 | } 320 | public static void main(String[] arg){ 321 | 322 | System.out.println("Hello"); 323 | } 324 | } 325 | 326 | 327 | output: 328 | 329 | Exception : Recursive constructor invocation. 330 | 331 | case 2 : 332 | class P{ 333 | 334 | } 335 | 336 | class C extends P{ 337 | 338 | } 339 | 340 | valid 341 | 342 | 343 | class P{ 344 | P(){ 345 | 346 | } 347 | } 348 | 349 | class C extends P{ 350 | 351 | } 352 | 353 | valid 354 | 355 | class P{ 356 | P(int n){ 357 | } 358 | } 359 | 360 | class C extends P{ 361 | 362 | } 363 | 364 | invalid : can not find symbol Symbol : constructor P() location :class P 365 | 366 | Note 1 : 367 | 368 | 1. if parent class contains any argument constructor then while writting child classes we have to take special care with respect to constructors. 369 | 370 | 2. whenever we are writting any argument constructor it is highly recommanded to write no-arg constructor also. 371 | 372 | case 3 : 373 | 374 | class Parent{ 375 | Parent() throws IOException{ 376 | 377 | } 378 | } 379 | class Child extends Parent{ 380 | Child(){ 381 | super(); 382 | } 383 | } 384 | output: 385 | CE : UnreportedException 386 | java.io.IOException in default constructor. 387 | e.g 2 388 | 389 | class Parent{ 390 | Parent() throws IOException{ 391 | 392 | } 393 | } 394 | class Child extends Parent{ 395 | Child()throws IOException|Exception|Throwable{ 396 | super(); 397 | } 398 | } 399 | 400 | 401 | output : compile fine 402 | 403 | NOte : 404 | 405 | if parent class throws any checked exception compulsary child class constructor should throw same checked exception or its parent. 406 | otherwise the code won't compile. 407 | 408 | 409 | Which of the following is valid 410 | 411 | a. the main purpose of constructor is to create an object. // invalid 412 | b. the main purpose of constructor is to perform initialization of an object. //valid 413 | c. the name of the constructor need not be same as class name. //invalid 414 | d. return type concept applicable for constructors but only void. //invalid 415 | e. we can apply any modifier for constructor. //invalid 416 | f. default constructor generated by JVM. //invalid 417 | g. compiler is responsible to generate default constructor. //valid 418 | h. compiler will always generate default constructor //invalid 419 | i. if we are not writting no-arg constructor then compiler will generate default constructor //invalid 420 | j. every no argument constructor is laways default constructor //false 421 | k. default constructor is always no-arg constructor. //true 422 | l. the first line every constructor should be either super() or this() if we 423 | are not writting anything then compiler will generates this(). //false 424 | 425 | m. for constructors both overloading and overrindding concepts are applicable //false 426 | 427 | n. for constructor inheritance concept applicable but not overridding //false 428 | o. only concrid classes can contain constructor but abstract classes can't //false 429 | p. interface can contain constructors //false 430 | q. recursive constructor invocation is a runtime exception. //invalid 431 | r. if parent class constructor throws some checked exception then compulsary child 432 | class constructor should throw same checked exception or its child //false 433 | 434 | 435 | -------------------------------------------------------------------------------- /java class_durgasoft/Coupling-and-typecasting: -------------------------------------------------------------------------------- 1 | _____________ 2 | Coupling 3 | _____________ 4 | 5 | The degree of dependency of components is called coupling. if dependency is more then it is considered as tightly coupling and if dependency is less then it is considered as loosly coupling. 6 | 7 | e.g 8 | 9 | class A{ 10 | static int a = B.j; 11 | } 12 | 13 | class B{ 14 | static int j = C.k; 15 | } 16 | 17 | class C{ 18 | static int k = D.m1(); 19 | } 20 | 21 | class D{ 22 | public static int m1(){ 23 | return 10; 24 | } 25 | } 26 | 27 | 28 | The above components are said to be tightly coupled with each other because dependency between the components is more 29 | 30 | Tightly coupling is not a good programming practice because it has several serious disadvantages. 31 | 32 | 1. without affecting remaining components we can't modify any component and hence enhancement will become difficult. 33 | 2. it suppresses re-usability. 34 | 3. it reduces maintainability of the application. 35 | 4. hence we have to maintain dependency between components as less as possible i.e. loosely coupling is good programming practice. 36 | 37 | _____________ 38 | Cohesion 39 | _____________ 40 | 41 | For every component a clear well defined functionality is required then that component is said to be follow high cohesion 42 | 43 | 44 | low cohesion 45 | ______________ 46 | 47 | Total Servlet 48 | 49 | login page display 50 | 51 | validation logic 52 | 53 | display in-box page 54 | 55 | display compose page 56 | 57 | display error page 58 | 59 | . 60 | . 61 | . 62 | . 63 | . 64 | . 65 | 66 | 67 | 68 | High cohesion 69 | ________________ 70 | 71 | login page----->validate servlet----------->if success--------------> inbox.jsp 72 | | 73 | | 74 | | not success 75 | | 76 | error.jsp 77 | 78 | 79 | High cohesion is always good programming practice because it has several advantages 80 | 1. without affecting remaining components we can modify any component hence enhancement will become easy 81 | 2. it promotes re-usability of the code(wherever validation is required we can reuse the same validation servlet without rewriting). 82 | 3. it improves maintainability of the application. 83 | 84 | Note : loosely coupling and high cohesion are good programming practices 85 | 86 | _____________________ 87 | Object typecasting 88 | _____________________ 89 | 90 | we can use parent reference to hold child object. 91 | 92 | e.g Object o = new String("Test"); 93 | 94 | we can use interface reference to hold implemented class object. 95 | 96 | e.g Runnable r = new Thread(); 97 | 98 | 99 | A b = (C) d; 100 | | | | | 101 | | | | | 102 | | | | | 103 | | | | | 104 | class| Name class| Reference 105 | interface of Interface variable 106 | name reference Name Name 107 | variable 108 | 109 | 110 | Mantra 1:(compile time checking 1) 111 | 112 | The type of 'd' and 'c' must have some relation either child to parent or parent to child or same type otherwise we will get compile time error 113 | saying inconvertable types found 'd' type required 'c'. 114 | 115 | e.g 1. valid 116 | 117 | Object o = new String("Test"); 118 | 119 | StringBuffer sb = (StringBuffer) o; 120 | 121 | e.g 2. invalid 122 | 123 | String s = new String("Test"); 124 | 125 | StringBuffer sb = (StringBuffer) s; 126 | 127 | CE: inconvertableTypes found java.lang.String required java.lang.StringBuffer 128 | 129 | Mantra 2:(compile time checking 2) 130 | 131 | 'C' must be either same or derived type of 'A' otherwise we will get compile time error saying incompatible types found : C required : A 132 | 133 | e.g 1. 134 | 135 | Object o = new String("Test"); 136 | 137 | StringBuffer sb = (StringBuffer) o; 138 | 139 | e.g 2. 140 | 141 | Object o = new String("Test"); 142 | 143 | StringBuffer sb = (String) o; 144 | 145 | CE: incompatible types found : java.lang.String required : java.lang.StringBuffer 146 | 147 | 148 | Mantra 3 : (runtime checking) 149 | 150 | Runtime object type of 'd' must be either same or derived type of 'c' otherwise we will get runtime exception saying ClassCastException 151 | 152 | e.g 1 153 | 154 | Object o = new String("Test"); 155 | 156 | StringBuffer sb = (StringBuffer) o; 157 | 158 | RE: ClassCastException : java.lang.String cannot be cast to java.lang.StringBuffer 159 | 160 | e.g 2 161 | 162 | Object o = new String("Test"); 163 | 164 | String sb = (String) o; 165 | 166 | valid 167 | 168 | e.g |-------------derived 1 169 | | 170 | |--------------base1--------| 171 | | | 172 | | |-------------derived 2 173 | Object---| 174 | | |-------------derived 3 175 | | | 176 | |--------------base2--------| 177 | | 178 | |-------------derived 4 179 | 180 | Base2 b = new Derived4(); 181 | 182 | a. Object o = (Base2) b; //valid 183 | b. Object o = (Base1) b; //invalid CE: inconvertable type found: Base2 required : Base1 184 | c. Object o = (Derived3) b; //invalid CE: ClassCastException 185 | d. Base2 b1 = (Base1) b; //invalid CE: inconvertable type found: Base2 required : Base1 186 | e. Base1 b1 = (Derived4) b; //invalid CE: incompatable type found: Derived4 required : Base1 187 | f. Base1 b1 = (Derived1); //invalid CE: inconvertable type found: Base2 required : Derived 1. 188 | 189 | Strictly speaking throw type casting we are not creating any new object. 190 | For the existing object we are providing another type of reference variable i.e we are performing type casting but not object casting. 191 | 192 | e.g 1. 193 | String s = new String("Test"); 194 | 195 | Object o = (Object) s; 196 | 197 | e.g 2. 198 | 199 | Integer i = new Integer(10);----------|------------------------------------| 200 | |------Number n = new Integer(10); | 201 | Number n = (Number) i; ---------------|------------------------------------|------------Object o = new Integer(10); 202 | | 203 | Object o = (Object) n;-----------------------------------------------------| 204 | 205 | sopln(i == n); 206 | sopln(n == o); 207 | 208 | 209 | Integer i-----------| 210 | | 211 | Number n------------|-------->10 212 | | 213 | Object o------------| 214 | 215 | 216 | A 217 | Note : /\ 218 | | 219 | C c = new C(); | 220 | | 221 | B b = new C();<--(B)c | 222 | B 223 | /\ 224 | | 225 | A a = new C();<--(A)((B)c) | 226 | | 227 | | 228 | C 229 | 230 | 231 | e.g 1. 232 | 233 | class P{ 234 | public void m1(){} 235 | } 236 | 237 | class C extends P{ 238 | public void m2(){} 239 | } 240 | 241 | C c = new C(); 242 | 243 | c.m1(); //valid 244 | 245 | c.m2(); //valid 246 | 247 | ((p)c).m1(); //valid 248 | 249 | ((p)c).m2(); //invalid Reason. parent reference can be used to hold child object but by using that reference we can't call child specific methods and we can call only the methods available in parent class. 250 | 251 | e.g 2. 252 | 253 | class A{ 254 | public void m1(){ 255 | System.out.println('A'); 256 | } 257 | } 258 | 259 | class B extends A{ 260 | public void m1(){ 261 | System.out.println('B'); 262 | } 263 | } 264 | 265 | class C extends B{ 266 | public void m1(){ 267 | System.out.println('C'); 268 | } 269 | } 270 | 271 | 272 | C c = new C(); // C 273 | 274 | ((B) c).m1(); // C 275 | 276 | ((A)((B) c)).m1(); // C 277 | 278 | 279 | It is overriding and method resolution is always based on runtime object type. 280 | 281 | e.g 3. 282 | class A{ 283 | public static void m1(){ 284 | System.out.println('A'); 285 | } 286 | } 287 | 288 | class B extends A{ 289 | public static void m1(){ 290 | System.out.println('B'); 291 | } 292 | } 293 | 294 | class C extends B{ 295 | public static void m1(){ 296 | System.out.println('C'); 297 | } 298 | } 299 | 300 | 301 | C c = new C(); // C 302 | 303 | ((B) c).m1(); // B 304 | 305 | ((A)((B) c)).m1(); // A 306 | 307 | It is method hiding and method resolution is always based on reference type. 308 | 309 | e.g 4 310 | 311 | class A{ 312 | int x = 777; 313 | } 314 | 315 | class B extends A{ 316 | int x = 888; 317 | } 318 | 319 | class C extends B{ 320 | int x = 999; 321 | } 322 | 323 | 324 | C c = new C(); 325 | 326 | sopln(c.x) // 999 327 | 328 | sopln(((B) c).x); // 888 329 | 330 | sopln(((A)((B) c)).x); // 777 331 | 332 | variable resolution is always based on reference type but not based on run-time object. 333 | 334 | 335 | -------------------------------------------------------------------------------- /java class_durgasoft/Singleton class: -------------------------------------------------------------------------------- 1 | Singleton classes 2 | ___________________ 3 | 4 | For any java class if we are allowed to create only one object such type of class is called singleton class. 5 | 6 | e.g Runtime 7 | business deligate 8 | service locator 9 | etc. 10 | 11 | Advantage of singletone class : 12 | _________________________________ 13 | 14 | if several people have same requirement then it is not recommanded to create seprate object for every requirement. 15 | We have to create only one object and we can reuse same object for every similar requirement so that performance and memory utilizations will be improved. 16 | 17 | This is the central idea of singleton classes. 18 | 19 | e.g 20 | Runtime r1 = Runtime.getRuntime(); 21 | Runtime r2 = Runtime.getRuntime(); 22 | . 23 | . 24 | . 25 | . 26 | Runtime rn = Runtime.getRuntime(); 27 | 28 | How to create our own singleton classes? 29 | _________________________________________ 30 | we can create our own singleton classes for this we have to use private constructor and private static variable and public factory method. 31 | 32 | approach 1. 33 | 34 | class Test{ 35 | private static Test testSingleton = new Test(); 36 | 37 | private Test(){ 38 | 39 | } 40 | public static Test getTest(){ 41 | return testSingleton; 42 | } 43 | } 44 | 45 | Test t1 = Test.getTest(); 46 | Test t2 = Test.getTest(); 47 | Test t3 = Test.getTest(); 48 | 49 | Note : Runtime class is internally implemented by using this approach. 50 | 51 | Approach 2. 52 | 53 | class Test{ 54 | private static Test testSingleton; 55 | 56 | private Test(){ 57 | 58 | } 59 | public static Test getTest(){ 60 | if(testSingleton == null){ 61 | testSingleton = new Test(); 62 | } 63 | return testSingleton; 64 | } 65 | } 66 | 67 | 68 | At any point of time for test class we can create only one object hence test class is singleton class. 69 | 70 | class is not final but we are not allowed to create child classes How it is possible. 71 | 72 | by declaring every constructor as private we can restrict child class creation. 73 | 74 | e.g 75 | 76 | class P{ 77 | private P(){} 78 | } 79 | 80 | for the above class it is impossible to create child class.s 81 | -------------------------------------------------------------------------------- /java class_durgasoft/Some IMP Points: -------------------------------------------------------------------------------- 1 | Inside static block or static method if we are accessing null object values then we will get following error 2 | 3 | Exception in thread "main" java.lang.ExceptionInInitializerError 4 | Caused by: java.lang.NullPointerException 5 | at StaticFlowTest.m1(StaticFlowTest.java:21) 6 | at StaticFlowTest.(StaticFlowTest.java:7) 7 | 8 | Inside instance block or method if we are accessing null object values the we will get following error 9 | 10 | Exception in thread "main" java.lang.NullPointerException 11 | at InstanceTest.m1(InstanceTest.java:21) 12 | at InstanceTest.(InstanceTest.java:5) 13 | 14 | -------------------------------------------------------------------------------- /java class_durgasoft/Types of variables: -------------------------------------------------------------------------------- 1 | _____________________ 2 | Types of variables 3 | _____________________ 4 | 5 | Based on type of value represented by a variable all variables are devided into two types. 6 | 7 | 1. premitive variables 8 | 2. reference variables 9 | 10 | 1. premitive variables : can be used to represent premitive values 11 | 12 | e.g int x = 10; 13 | 14 | 2. reference variables : can be used to referrer objects 15 | 16 | e.g student s = new Student(); 17 | 18 | Division 2 19 | _____________ 20 | 21 | Based on position of declaration and behaviourall variables are devided into 3 types 22 | 23 | 1. instance variables 24 | 2. static variables 25 | 3. local variables 26 | 27 | _____________________ 28 | Instance variables 29 | _____________________ 30 | 31 | 1. if the value of a variable is varied from object to object such type of variables are called instance variables. 32 | 2. for every object a seprate copy of instance variables will be created. 33 | 34 | 3. Instance variables hould be declared within the class directly but outside of ant method or block or constructor. 35 | instance variable will be created at the time of object creation and destroyed at the time of object distruction hence the scope of instance 36 | variable is exactly same as the scope of object. 37 | 38 | Instance variables will be stored in the heap memory as a part of object 39 | we can't access instance variables directly from static area. 40 | 41 | But we can access by using object reference. 42 | 43 | but we can access instance variables directly from instance area. 44 | 45 | e.g 46 | 47 | class Test{ 48 | int x = 10; 49 | public static void mina(String[] args){ 50 | sopln(x);------------------------------> // invalid CE:Non static variable x cannot be referenced from a static context. 51 | Test t1 = new Test(); 52 | sopln(t1.x);---------------------------> //valid output : 10 53 | } 54 | 55 | public void sum(){ 56 | sopln(x); 57 | } 58 | } 59 | 60 | for Instance variables JVM will always provide default values and we are not required to perform initialization explicitly. 61 | 62 | e.g 63 | class Test{ 64 | int x; 65 | double d; 66 | boolean b; 67 | String s; 68 | public static void main(String[] args){ 69 | Test t1 = new Test(); 70 | sop(t1.x);------------------------>0 71 | sop(t1.d);------------------------>0.0 72 | sop(t1.b);------------------------> false 73 | sop(t1.s);------------------------> null 74 | } 75 | } 76 | 77 | instance variables also known as object level variables or attributes. 78 | 79 | ____________________ 80 | static variables 81 | ____________________ 82 | 83 | if the value of a variable is not varied from object to object then it is not recommanded to declare variable as instance variable. we have to declare such type of variables at class level by using static modifier. 84 | 85 | In the case of instance variables for every object a seperet copy will be creaed but in the case of static variables a single copy will be creaed at class level and shared by every object of the class. 86 | 87 | Static variables should be declared within the class directly but outside of any method or block or constructor. 88 | 89 | Static variables will be created at the time of class loading and destroyed at the time of class unloading hence scope of static variable is exactly same as scope of .class file. 90 | 91 | 92 | Load class by JVM 93 | 94 | 1. Start JVM 95 | 2. create and start main thread 96 | 3. locate Test.class File 97 | 4. Load Test.class---------------->Start static variable initialization 98 | 5. Execute Main() Thread. 99 | 6. Unload Test class---------------->Start static variable deinitialization 100 | 7. Terminate main thread 101 | 8. shutdown JVM. 102 | 103 | Static variables will be stored in method area. 104 | 105 | we can access static variables either by object reference or by class name but recommanded to use class name. 106 | within the same class it is not required to use class name and we can access directly. 107 | 108 | class Test{ 109 | static int x = 10; 110 | public static void main(String[] args){ 111 | Test t = new Test(); 112 | sop(t.x);-----------------------------> Valid 113 | sop(Test.x);-----------------------------> Valid 114 | sop(x);-----------------------------> Valid 115 | } 116 | } 117 | 118 | we can access static variables directly from both instance and static areas. 119 | e.g 120 | 121 | class Test{ 122 | static int x = 10; 123 | public static void main(String[] args){ 124 | sopln(x); 125 | } 126 | public void display(){ 127 | sopln(x); 128 | } 129 | } 130 | 131 | for static variables JVM will provide default values and we are not required to perform initialization explicitly 132 | 133 | class Test{ 134 | static int x; 135 | static double d; 136 | static String s; 137 | public static void main(String[] args){ 138 | sopln(x);--------------------------->// valid 0 139 | sopln(d);--------------------------->// valid 0.0 140 | sopln(s);--------------------------->// valid null 141 | } 142 | } 143 | 144 | static variables also known as class level veriables or fields. 145 | 146 | class Test{ 147 | static int x = 10; 148 | int y = 20; 149 | public static void main(String[] args){ 150 | Test t1 = new Test(); 151 | t1.x = 888; 152 | t1.y = 999; 153 | Test t2 = new Test(); 154 | sopln(t2.x + "............" + t2.y);----------------------->// output : 888...........20 155 | } 156 | } 157 | 158 | ________________ 159 | Local Variable | 160 | ________________| 161 | 162 | 1. some times to meet temperary requirements of the programmer we can declare variables inside a method or block or constructor such type of variables are called local variables or temporary variables or stack variables or automatic variables 163 | 164 | 2. local variables will be stored inside stack memory. 165 | 166 | 3. local variables will be created while executing block in which we declared it.once block execution complete automatically local variable will be destroyed hence the scope of local variable is the block in which we declared it. 167 | 168 | e.g 169 | 170 | class Test{ 171 | public void static main(String[] args){ 172 | int i = 3; 173 | 174 | for(int j = 0 ; j < 5; j++){ 175 | i = i + 1; 176 | } 177 | sopln(i + "......" + j );------------------> // invalid : CE: cannot find symbol variable : J class : Test 178 | } 179 | } 180 | 181 | class Test{ 182 | public void static main(String[] args){ 183 | int i = 3; 184 | try{ 185 | int j = Integer.parseInt("ten"); 186 | 187 | } catch(NumberFormatException e){ 188 | sopln(j);------------------> // invalid : CE: cannot find symbol variable : J class : Test 189 | } 190 | sopln(j);------------------> // invalid : CE: cannot find symbol variable : J class : Test 191 | 192 | } 193 | } 194 | 195 | Note : for local variables jvm won't provide default value compulsary we should perform initialization explicitly before using that variables that is if we are not using then it is not required to perform initialization. 196 | 197 | e.g 1. 198 | class Test{ 199 | public static void main(String[] args){ 200 | int x; 201 | sop("Hello"); 202 | } 203 | } 204 | 205 | output : 206 | Hello 207 | e.g 2. 208 | class Test{ 209 | public static void main(String[] args){ 210 | int x; 211 | sop(x);------------------------------------> // invalid variable x might not have been initialization. 212 | } 213 | } 214 | 215 | class Test{ 216 | public static void main(String[] args){ 217 | int x; 218 | if(args.length > 0){ 219 | x = 10; 220 | } 221 | sop(x);------------------------------------> // invalid variable x might not have been initialization. 222 | } 223 | } 224 | 225 | 226 | class Test{ 227 | public static void main(String[] args){ 228 | int x; 229 | if(args.length > 0){ 230 | x = 10 231 | } else{ 232 | x = 20; 233 | } 234 | sop(x); 235 | } 236 | } 237 | 238 | output : 20 239 | 240 | 241 | Note 1 : it's not recommanded to perform initialization for local variables inside local blocks because there is no gauranty for the execution of these blocks always at runtime. 242 | 243 | Note 2 : it's highly recommanded to perform initialization for locla variables at the time of declaration atlist with default values. 244 | 245 | Note 3 : the only applicable modifier for local variables is final by mistake if we are trying to apply any other modifier then we will get compile time error. 246 | 247 | public int x = 10;______________ 248 | private int x = 10; | 249 | protected int x = 10; | invalid ------>illegalStartOfExpression. 250 | static int x = 10; | 251 | transient int x = 10; | 252 | volatile int x = 10;____________| 253 | 254 | final int x = 10;------> //valid 255 | 256 | Note : if we are not declaring with any modifier then by default it is default but this rule is applicable only for instance and static variables but not for local variables. 257 | ______________ 258 | Conclusions * 259 | ______________* 260 | 261 | 1. For instance and static variables JVM will provide default balues and we are not required to perform initialization explicitly but for local variables jvm won't provide default values compulsary we should perform initialization explicitly before using that variable. 262 | 2. instance and static variables can be accessed by muliple thread symulteniously and hence these are not thread safe but in the case of local variables for every thread a seprate copy will be created and hence local variables are thread safe. 263 | 264 | ___________________________________________________________ 265 | Type of variable is thread safe or not | 266 | ___________________________________________________________| 267 | | 268 | instance variable not | 269 | | 270 | static variable not | 271 | | 272 | local variable yes | 273 | ___________________________________________________________| 274 | 275 | 1. Every variable in java should be eithrer instance or static or local. 276 | 2. Every variable in java should be eithr premitive or reference hence variouse possible combinations of variables in java are 277 | 278 | instance - premitive 279 | static - premitive 280 | local - premitive 281 | 282 | instance - reference 283 | static - reference 284 | local - reference 285 | 286 | 287 | class Test{ 288 | int x = 0;----------------------------> instance premitive 289 | static String = "testing";------------> static reference 290 | 291 | public static void main(String[] args){ 292 | int[] y = new int[3];--------------------------->local reference 293 | 294 | } 295 | } 296 | 297 | _______________________ 298 | UnInitialized arrays 299 | _______________________ 300 | 301 | class Test{ 302 | int[] x ; 303 | public static void main(String[] args){ 304 | Test t = new Test(); 305 | sopln(t.x); ------------------------->null 306 | sopln(t.x[0]); -------------------------> NullPointerVariableException 307 | } 308 | } 309 | 310 | I. Instance leven 311 | 1. int[] x; 312 | sopln(objct.x);------------->null 313 | sopln(objct.x[0]);---------->NPVE 314 | 315 | 2. int[] x = new int[3]; 316 | sopln(objct.x);-------> [I@45ef68 317 | sopln(objct.x[0]);----> 0 318 | 319 | II. static level 320 | 321 | 1. static int[] x; 322 | sopln(objct.x);------------->null 323 | sopln(objct.x[0]);---------->NPVE 324 | 325 | 2. static int[] x = new int[3]; 326 | sopln(objct.x);-------> [I@45ef68 327 | sopln(objct.x[0]);----> 0 328 | 329 | III. local level 330 | 331 | 1. int[] x; 332 | sopln(objct.x);------------->CE : variable x might not have been initialized. 333 | sopln(objct.x[0]);---------->CE : variable x might not have been initialized. 334 | 335 | 2. int[] x = new int[3]; 336 | sopln(objct.x);-------> [I@45ef68 337 | sopln(objct.x[0]);----> 0 338 | 339 | Note : once we creates an array every array element by default initialized with default values. Errespective of whether it is instance or static or local array. 340 | -------------------------------------------------------------------------------- /java class_durgasoft/arrays in java: -------------------------------------------------------------------------------- 1 | Arrays : 2 | ----------------- 3 | 4 | 1. Introduction. 5 | 2. Array declaration. 6 | 3. Array Creation. 7 | 4. Array initialization. 8 | 5. Array Declaration, Creation and initialization in a single line. 9 | 6. length vs length() 10 | 7. annonymus arrays. 11 | 8. Array element assignments, 12 | 9. array variable assignment. 13 | 14 | _______________ 15 | Introduction 16 | _______________ 17 | 18 | 1. An array is an indexed collection of fixed number of homogenious data elements. 19 | 2. The main advantage of arrays is we can represent huge number of values by using single variables so that readability of the code will be improved. 20 | But main disadvantage of arrays is fixed in size that is once we creates an array there is no chance of increasing or decreasing the size based on our requirement. Hence to use arrays concept compulsary we should know the size in advance, which may not possible always. 21 | 22 | _______________________ 23 | Array Declaration 24 | _______________________ 25 | 26 | 27 | one dimentional array declaration. 28 | ____________________________________ 29 | 30 | int[] x; valid// recommanded because name is clearly seprated from type. 31 | 32 | int []x; valid 33 | 34 | int x[]; valid 35 | 36 | at the time of declaration we can't specify the size otherwise we will get compile time error. 37 | 38 | int[6] x; invalid 39 | 40 | int[] x; valid 41 | 42 | Two dimentional array declaration 43 | _____________________________________ 44 | 45 | int[][] x; 46 | int [][]x; 47 | int x[][]; 48 | int[] []x; 49 | int[] x[]; 50 | int []x[]; 51 | 52 | Q. which of the following are valid? 53 | 54 | a. int[] a, b; valid a---> 1 dimention, b---> 1 dimention. 55 | b. int[] a[], b; valid a---> 2 dimention, b---> 1 dimention. 56 | c. int[] a[], b[]; valid a---> 2 dimention, b---> 2 dimention. 57 | d. int[] []a, b; valid a---> 2 dimention, b---> 2 dimention. 58 | e. int[] []a, b[]; valid a---> 2 dimention, b---> 3 dimention. 59 | f. int[] []a, []b; invalid. CE : ';' Expected 60 | 61 | 1. if we want to specify dimention before the variable that facility is aplicable only for first variable in a declaration. 62 | 2. if we are trying to apply for remaining variable we will get compile time error. 63 | e.g 64 | int[] []a, []b, []c; 65 | | | | 66 | | | | 67 | | | | 68 | | | | 69 | | | | 70 | valid invalid invalid 71 | 72 | Three dimentional array declaration 73 | ____________________________________ 74 | 75 | int[][][] a; valid 76 | int [][][]a; valid 77 | int a[][][]; valid 78 | int[] [][]a; valid 79 | int[] a[][]; valid 80 | int[] []a[]; valid 81 | int[][] []a; valid 82 | int[][] a[]; valid 83 | int [][]a[]; valid 84 | int []a[][]; valid 85 | 86 | 87 | Array Creation 88 | ____________________ 89 | 90 | Every array in java is an object only hence we can create arrays by using new operator. 91 | 92 | e.g int[] a = new int[3]; valid 93 | 94 | for every array type corresponding classes are available and thses classes are part of java language and not available to the programer level 95 | 96 | 97 | e.g int[] a = new int[3]; valid 98 | 99 | sop(a.getClass().getName()); 100 | 101 | output : 102 | [I 103 | 104 | 105 | Array Type Corresponding class name 106 | 107 | int[] [I 108 | int[][] [[I 109 | double[] [D 110 | short[] [S 111 | long[] [L 112 | byte[] [B 113 | 114 | boolean[] [Z 115 | 116 | 117 | 1. At the time of array creation compulsary we should specify the size otherwise we will get compile time error. 118 | e.g int[] x = new int[]; invalid //CE : Array Dimension missing 119 | int[] x = new int[6]; valid 120 | 121 | 2. It is legal to have an array with size 0 in java. 122 | 123 | e.g int[] x = new int[0]; 124 | 125 | 3. If we are trying to specify array size with some negative int value then we will get runtime exception saying negativeArraySizeException. 126 | 127 | e.g int[] x = new int[-3]; invalid // Runtime Exception : NegativeArraySizeException 128 | 129 | 130 | 4. To specify array size allowed data types are 131 | 1. byte, 2. short, 3. char, 4. int 132 | 133 | if we are trying to specify any other type then we will get Compile time error. 134 | 135 | int[] a = new int[10]; valid 136 | int[] a = new int['c']; valid 137 | byte b = 10; 138 | int[] b = new int[b]; valid 139 | short s = 10; 140 | int b = new int[s]; valid 141 | 142 | int[] a = new int[10l]; invalid CE : Possible loss of precision 143 | found : long 144 | required : int 145 | 146 | 5. The maximum allowed array size in java is 2147483647 which is the maximum value of int data type. 147 | 148 | int[] a = new int[2147483647]; valid 149 | int[] a = new int[2147483648]; invalid CE: integer number too large. 150 | 151 | 6. even in the first case we may get runtime exception if sufficient heap memory not available. 152 | OutOfMemoryError : Requested array size exceed vm limit 153 | 154 | _________________________________ 155 | 2 Dimentional array creation 156 | _________________________________ 157 | 158 | in java 2 dimentional array not implemented by using matrix style sun people followed array of arrays approach for multidimentional array creation. 159 | 160 | the main advantage of this approach is memory utilization will be improved. 161 | 162 | e.g 1. int[][] x = new int[5][]; 163 | x[0] = new int[2]; 164 | x[1] = new int[4]; 165 | 166 | e.g 2. int[][][] x = new int[2][][]; 167 | x[0] = new int[2][]; 168 | x[0][0] = new int[1]; 169 | x[0][1] = new int[2]; 170 | x[0][2] = new int[3]; 171 | x[1] = new int[2][2]; 172 | 173 | 174 | Q. which of the following array declarations are valid. 175 | 176 | int[] a = new int[]; invalid 177 | int[] a = new int[3]; valid 178 | int[][] a = new int[][]; invalid 179 | int[][] int = a new[3][]; valid 180 | int[][] a = new int[][4]; invalid 181 | int[][] a = new int[3][4]; valid 182 | int[][][] a = new int[3][4][5]; valid 183 | int[][][] a = new int[3][4][]; valid 184 | int[][][] a = new int[3][][5]; invalid 185 | int[][][] a = new int[][4][5]; invalid 186 | 187 | _______________________ 188 | Array Initialization 189 | _______________________ 190 | 191 | once we creates an array every element by default initialized with default values. 192 | 193 | e.g 1. int[] x = new int[3]; 194 | 195 | SOP(s); 196 | SOP(s[0]); 197 | 198 | output : 199 | [I@2e4534 200 | 0 201 | 202 | 203 | Note : Whenever we are trying to print any reference variable internally toString() method will be called. 204 | which is implemented by default to return the string in the following form 205 | 206 | classname@Hashcode in hexadecimal form 207 | 208 | e.g 2. 209 | int[][] x = new int[3][2]; 210 | 211 | sop(x); 212 | sop(x[0]); 213 | sop(x[0][0]); 214 | 215 | outpupt: 216 | [[I@4F5f45 217 | [I@45e4e45 218 | 0 219 | 220 | e.g 3. int[][] x = new int[3][]; 221 | sop(x); 222 | sop(x[0]); 223 | sop(x[0][0]); 224 | 225 | output : 226 | RuntimeException: NullPointerException 227 | 228 | Note : 229 | if we are trying to perform any operation on null then we will get runtime exception saying NullPointerException. 230 | 231 | once we creates an array every array element by default initialized with default values. If we are not satisfied with default values then 232 | we can override these values with our customized values. 233 | 234 | e.g 235 | int[] x = new int[6]; 236 | 237 | x[0] = 10; valid 238 | x[1] = 20; valid 239 | x[2] = 30; valid 240 | x[3] = 40; valid 241 | x[4] = 50; valid 242 | x[5] = 60; valid 243 | x[6] = 60; invalid : RE : ArrayIndexOutOfBond 244 | x[-6] = 60; invalid : RE : ArrayIndexOutOfBond 245 | x[2.5] = 60; invalid : CE : Possible loss of precision 246 | required : int 247 | found : double 248 | 249 | Note : if we are trying to access array element with outoff range index (either positive value or negative int value) then we will get 250 | runtime exception saying ArrayIndexOutofBoundException. 251 | 252 | 253 | __________________________________________________________________ 254 | Array Declaration, Creation and initialization in a single line. 255 | __________________________________________________________________ 256 | 257 | We can declare create and initialize an array in a single line(shortcut representation). 258 | 259 | int[] x; 260 | x = new int[3]; 261 | x[0] = 10; 262 | x[1] = 10; 263 | x[2] = 10; 264 | 265 | for this we have to write only one line. 266 | 267 | int[] x = {10,20,30}; 268 | char[] ch = {'a','e','i','o','u'}; 269 | String[] strarr = {"a", "aa", "aaa", "aaaa", "aaaaa"}; 270 | 271 | we can use this shortcut for multidimentional arrays also. 272 | 273 | int[][] x = {{1,2,3},{4,5,6,7}}; 274 | 275 | 276 | int [][][] x = {{{10,20,30},{40,50,60}},{{70,80}{90,100,110}}} 277 | 278 | Note : first represent above in memory representation form and then only solve it. 279 | 280 | 281 | sop(x[0][1][2]); //output : 60 282 | sop(x[1][0][1]); //output : 80 283 | sop(x[2][0][0]); //RE : ArrayIndexOutOfBondException 284 | sop(x[1][2][0]); //RE : ArrayIndexOutOfBondException 285 | sop(x[1][1][1]); //output : 100 286 | sop(x[2][1][0]); //RE : ArrayIndexOutOfBondException 287 | 288 | 289 | if we want to use this shortcut compulsary we should perform all activities in a single line. If we are trying to devide in two multiple lines 290 | then we will get compile time error. 291 | 292 | e.g int[] x = {10,20,30}; valid 293 | 294 | int[] x; 295 | x = {10,20,30}; invalid CE:IllegalStartOfExpression 296 | 297 | ______________________ 298 | length vs length() : 299 | ______________________ 300 | 301 | length variable represents the size of the array. 302 | length is a final variable applicable for arrays 303 | 304 | 305 | e.g int[] x = new int[6]; 306 | 307 | sop(x.length()); 308 | 309 | output : 310 | CE: cannot find symbol method : length() in class [I type 311 | 312 | sop(x.length); 313 | 314 | output : 6 315 | 316 | length() method is a final method applicable for string objects length method returns number of characters present in the string. 317 | 318 | e.g String s = "test"; 319 | sop(s.length()); 320 | 321 | CE:cannot find symbol Variable : length() 322 | location : java.lang.string. 323 | 324 | sop(s.length); 325 | output: 326 | 4 327 | 328 | 329 | Note : length variable applicable for arrays but not for string objects where as length() method applicable for 330 | string objects but not for arrays. 331 | 332 | String[] s = {"a","aa","aaa"}; 333 | 334 | 1. sop(s.length); valid 335 | 2. sop(s.length()); invalid // CE : Can't find symbol method : length() location : length 336 | 3. sop(s[0].length); invalid // CE : Can't find symbol variable : length location : java.lang.String 337 | 4. sop(s[0].length()); valid 338 | 339 | in multi dimentional arrays length variable represents only base size but not total size 340 | 341 | e.g int[][] x = new int[6][3]; 342 | 343 | sop(x.length); // 6 344 | sop(x[0].length); // 3 345 | 346 | there is no direct way to find total length of multidimentional array. 347 | 348 | But indirectly we can find as follows. 349 | 350 | x[0].length + x[1].length + .... 351 | 352 | __________________________ 353 | Annonymous Arrays 354 | __________________________ 355 | 356 | Some times we can declare an array without name, such type of nameless arrays are called annonymous arrays. 357 | the main purpose of annonymous arrays is just for instant use (one time usage). 358 | 359 | we can create annonymous array as follows 360 | 361 | new int[]{10,20,30,40}; 362 | 363 | while creating annonymous arrays we can't specify the size. 364 | otherwise we will get compile time error. 365 | 366 | new int[3]{10,20,30}; // invalid 367 | new int[]{10,20,30}; // valid 368 | 369 | we can create multidimentional annonymous arrays also 370 | 371 | new int[][] {{10,20}, {30,40,50}}; 372 | 373 | based on our requirement we can give the name for annonymous array then it is no longer annonymous 374 | 375 | int[] x = new int[]{10,20,30}; 376 | 377 | e.g 378 | 379 | class TestAnnonymousArray{ 380 | public static void main(String[] args){ 381 | sum(new int[]{10,20,30}); 382 | } 383 | 384 | public static void sum(int[] x){ 385 | int total = 0; 386 | for(int i = 0; i < x.size; i++){ 387 | total += x[i]; 388 | } 389 | sop("the sum is : " + total); 390 | } 391 | } 392 | 393 | in the above example just to call sum() method we required an array. But after completing sum() method call we are not using that array any more 394 | hence for this one time requirement annonymous array is the best choice. 395 | 396 | __________________________ 397 | Array elements assignments 398 | __________________________ 399 | 400 | case 1 : in the case of premitive type array as array elements we can provide any type which can be implecitly promoted to declared type. 401 | e.g 402 | int[] x = new int[5]; valid 403 | x[0] = 10; valid 404 | x[0] = 'a'; valid 405 | byte b = 30; valid 406 | x[1] = 'b'; valid 407 | short sh = 20; valid 408 | x[1] = sh; valid 409 | s[4] = 10l; invalid // CE : PLP Found : long 410 | required : int 411 | 412 | e.g 2. 413 | 414 | in the case of float type arrays allowed datatypes are byte, short, char, int, long, float. 415 | 416 | case 2 : in the case of object type arrays as array elements we can provide either declared type objects or its child class objects. 417 | e.g 1. Object[] a = new Object[10]; 418 | a[0] = new Object(); // valid 419 | a[1] = new String("Test"); // valid 420 | a[3] = new Integer(30); // valid 421 | 422 | e.g 2 423 | Number[] n = new Number[10]; 424 | n[1] = new Integer(20); //valid 425 | n[1] = new Double(20.5);//valid 426 | n[2] = new String("test"); //invalid CE : incompaitable type found : java.lang.String required java.lang.Number. 427 | 428 | case 3: for interface type array as array elements it's implementation class objects are allowed. 429 | 430 | Runnable[] r = new Runnable[10]; 431 | r[0] = new Thread();// valid 432 | r[1] = String("Test"); // invalid CE:incompatable types found java.lang.String required java.lang.Runnable 433 | 434 | Implements 435 | Thread----------------------------->Runnable 436 | 437 | 438 | Array type Allowed element type 439 | 440 | 1. Premitive arrays Any type which can be implecitly promoted to declared type. 441 | 2. object type arrays Either declared type or its child class object 442 | 3. abstract class arrays its child class objects are allowed. 443 | 4. Interface type arrays its implementation class objects are allowed. 444 | 445 | 446 | _______________________________ 447 | Array Variable assignments 448 | _______________________________ 449 | 450 | Case 1 : element level promotions are not applicable at array level. 451 | 452 | e.g char element can be promoted to int type. Wherer as char array cannot be promoted to int array. 453 | 454 | e.g. int[] x = {10,20,30,40}; 455 | char[] ch = {'a','b','c','d'}; 456 | 457 | int y = x;//valid 458 | int n = ch;// invalid CE:Found char array required int array. 459 | 460 | Q. Which of the following promotions will be performed automatically. 461 | 462 | 1. char -----> int. 463 | 2. char[] -----> int[]. 464 | 3. int -----> double. 465 | 4. int[] -----> double[]. 466 | 5. float -----> int. 467 | 6. float[] -----> int[]. 468 | 7. String -----> Object. 469 | 8. String[] -----> Object[]. 470 | 471 | but in the case of object type arrays child class type array can be promoted to parent class type array 472 | 473 | e.g String[] s = {"a","b","C","d"}; 474 | Object[] obj = s; 475 | 476 | Whenever we are assigning one array to another array internal elements won't be compied just reference elements will be reassigned 477 | 478 | int[] a = {10, 20, 30, 40}; 479 | int[] b = {50, 60}; 480 | 481 | a = b;// valid 482 | b = a;// valid 483 | 484 | Case 3 : whenever we are assigning one array to another array dimentions must be matched 485 | 486 | e.g in the place of one dimentional int array we should provide one dimentional array only if we are trying to provide any other dimention then we will get compile time error. 487 | 488 | e.g int[][] a = new int[][]; 489 | a[0] = new int[][]; //invalid CE: incompatable type found: int[][] required : int[]. 490 | a[0] = 10; //invalid CE: incompatable type found: int required : int[]. 491 | a[0] = new int[2]; valid 492 | 493 | Note : whenever we are assigning one array to another array bothe dimentions and types must be matched but sizes are not required to match. 494 | _______________ 495 | for SCJP | 496 | _______________| 497 | e.g 1 498 | 499 | class Test{ 500 | public static void main(String[] args){ 501 | for(int i = 0; i <= args.length; i++){ 502 | sop(args[i]); 503 | } 504 | } 505 | } 506 | 507 | While Execution : 508 | 509 | java Test a b c 510 | 511 | RE : ArrayIndexOutOfBondException 512 | java Test a b 513 | 514 | RE : ArrayIndexOutOfBondException 515 | java Test a 516 | 517 | RE : ArrayIndexOutOfBondException 518 | 519 | because of size of array is 3 and for loop will execute 4 times and at last iteration it will get failed. 520 | 521 | e.g 2. 522 | class Test{ 523 | public static void main(String[] args){ 524 | String[] argh = {"x","y","b"}; 525 | args = argh;------------------------------------------->observe this line 526 | for(int i = 0; i <= args.length; i++){ 527 | sop(args[i]); 528 | } 529 | } 530 | } 531 | 532 | java Test a b c 533 | 534 | output : 535 | x 536 | y 537 | z 538 | java Test a b 539 | 540 | output : 541 | x 542 | y 543 | z 544 | 545 | java Test a 546 | 547 | output : 548 | x 549 | y 550 | z 551 | 552 | e.g 3. 553 | 554 | int[][] a = new [4][5]; 555 | a[0] = new int[4]; 556 | a[1] = new int[3]; 557 | 558 | a = new int[3][2]; 559 | 560 | a. Total how many objects are created. 561 | 562 | Ans : 11 563 | 564 | b. Total how many objects are eligible for garbage collection? 565 | 566 | Ans : 7 567 | 568 | 569 | -------------------------------------------------------------------------------- /java class_durgasoft/chapter names: -------------------------------------------------------------------------------- 1 | 1. Language fundamentals. ->done 2 | 2. Operators and assignments ->done 3 | 3. flow control ->done 4 | 4. Declaration and access modifiers. ->done 5 | 5. oops ->done 6 | 6. Exception handling ->done 7 | 7. multi threading ->done 8 | 8. Multi threading inhancements.->partially done 9 | 9. Inner classes ->done 10 | 10. java.lang.package. ->done 11 | 11. File I/O 12 | 12. serialization 8 13 | 14. collections 14 | 15. Generics ->done 15 | 16. garbage collection ->done 16 | 17. 17 | 18. internationalization 18 | 19. Development ->5 19 | 20. Assertion. -> 20 | 21. java architecture. 21 | 22 | 23 | 24 | multi threading 25 | Multi threading inhancements 26 | File I/O 27 | serialization 28 | collections 29 | Generics 30 | internationalization 31 | Assertion 32 | java architecture 33 | -------------------------------------------------------------------------------- /java class_durgasoft/chapter names~: -------------------------------------------------------------------------------- 1 | 1. Language fundamentals. ->done 2 | 2. Operators and assignments ->done 3 | 3. flow control ->done 4 | 4. Declaration and access modifiers. ->done 5 | 5. oops ->done 6 | 6. Exception handling ->done 7 | 7. multi threading ->done 8 | 8. Multi threading inhancements.->partially done 9 | 9. Inner classes ->done 10 | 10. java.lang.package. ->done 11 | 11. File I/O 12 | 12. serialization 8 13 | 14. collections 14 | 15. Generics ->done 15 | 16. garbage collection ->done 16 | 17. 17 | 18. internationalization 18 | 19. Development ->5 19 | 20. Assertion. -> 20 | 21. java architecture. 21 | 22 | 23 | 24 | multi threading 25 | Multi threading inhancements 26 | File I/O 27 | serialization 28 | collections 29 | Generics 30 | internationalization 31 | -------------------------------------------------------------------------------- /java class_durgasoft/control-flow: -------------------------------------------------------------------------------- 1 | ______________________ 2 | Static control flow 3 | ______________________ 4 | 5 | Whenever we are executing a java class the following sequence of activities or steps will be executed as the part of static control flow. 6 | 7 | 1. Identification of static members from top to bottom. step 1-6 8 | 2. execution of static variable assignments and static blocks from top to bottom. step 7-12 9 | 3. execution of main method. step 13-15 10 | 11 | e.g 12 | 13 | class Base{ 14 | 1-->static int i = 10;-->7 15 | 16 | 2-->static{ 17 | m1(); -->8,-->13 18 | System.out.println("First static block");-->10, -->15 19 | } 20 | 21 | 3-->public static void main(String[] args){ 22 | m1(); 23 | System.out.println("Main method"); 24 | } 25 | 26 | 4-->public static void m1(){ 27 | System.out.println(j);-->9,-->14 28 | } 29 | 30 | 5-->static{ 31 | sopln("Second static block");-->11 32 | } 33 | 34 | 6-->static int j = 20;-->12 35 | } 36 | 37 | RIWO : READ INDIRECTLY WRITE ONLY 38 | i = 0[RIWO]; 39 | j = 0[RIWO]; 40 | i = 10[RIWO]; 41 | j = 20[RIWO]; 42 | output: 43 | 44 | 0 45 | First Static block 46 | Second static block 47 | 20 48 | main method 49 | 50 | 1. Identification of static members from top to bottom. 51 | 2. Execution of static variable assignment and static block from top to bottom. 52 | 3. Execution of main method. 53 | 54 | 55 | RIWO : READ INDIRECTLY WRITE ONLY 56 | 57 | inside static block if we are trying to read a variable that read operation is called direct read. 58 | if we are calling a method and within that method if we are trying to read a variable that read operation is called indirect read. 59 | 60 | class Test{ 61 | static int i = 10; 62 | 63 | static{ 64 | sopln(i);------->direct read 65 | } 66 | public static void m1(){ 67 | sopln(i);------------->Indirect read 68 | } 69 | } 70 | 71 | if a variable is just identified by the jvm and original value not yet assigned then the variable is said to be Read Indirectly Write Only State[RIWO]. 72 | 73 | If a variable is in read indirectly write-only state then we can't perform direct read but we can perform indirect read. 74 | 75 | If we are trying to read directly then we will get compile time error saying IllegalForwardReference. 76 | 77 | e.g 1. 78 | 79 | class Test{ 80 | static int x = 10; 81 | 82 | static{ 83 | sopln(x); 84 | } 85 | } 86 | 87 | output: 88 | 10 89 | 90 | class Test{ 91 | static{ 92 | sopln(x); 93 | } 94 | static int x = 10; 95 | } 96 | 97 | x = 0;[RIWO] 98 | CE : illegal forward reference 99 | 100 | class Test{ 101 | static{ 102 | m1(); 103 | } 104 | public static void m1(){ 105 | sopln(x); 106 | } 107 | static int x = 10; 108 | } 109 | 110 | output: 111 | 112 | RE : NoSuchMethodFoundError: main() 113 | 114 | _____________________ 115 | static block 116 | _____________________ 117 | 118 | Static block will be executed at the time of class loading hence at the time of class loading if we want to perform any activity we have to define that inside static block. 119 | 120 | e.g 1. at the time of java class loading the corresponding native libraries should be loaded hence we have to define this activity inside static block 121 | 122 | class Test{ 123 | static{ 124 | System.loadLibrary("native library path"); 125 | } 126 | } 127 | 128 | 129 | e.g 2 After loading every database driver class we have to register driver class with driverManager. But inside database driver class there is a static block to perform this activity and we are not responsible to register explicitly 130 | 131 | class DBDriver{ 132 | static{ 133 | Register this driver with driver manager. 134 | } 135 | } 136 | 137 | Note : within a class we can declare any number of static blocks but all these static blocks will be executed from top to bottom. 138 | 139 | 140 | Q1. Without writing main() method is it possible to print some statements to the console. 141 | 142 | Ans : yes by using static block.(till 1.6 only. In 1.7 version we have compulsory to define main()) 143 | 144 | e.g class Test{ 145 | static{ 146 | System.out.println("I can print"); 147 | System.exit(0); 148 | } 149 | } 150 | 151 | output: 152 | 153 | I can print 154 | 155 | Q2. Without writing main() method and static block is it possible to print some statement to the console. 156 | 157 | Ans : YES off-course there are multiple ways. 158 | 159 | 160 | 1. 161 | class Test{ 162 | static int x = m1(); 163 | 164 | public static int m1(){ 165 | System.out.ptrintln("Hello I can print"); 166 | 167 | return 10; 168 | } 169 | } 170 | 171 | 2. 172 | class Test{ 173 | static Test t = new Test(); 174 | 175 | { 176 | System.out.ptrintln("Hi I can print"); 177 | System.exit(0); 178 | } 179 | } 180 | 181 | 182 | 3. 183 | 184 | class Test{ 185 | static Test t = new Test(); 186 | 187 | Test(){ 188 | System.out.ptrintln("Hello hi I can print"); 189 | System.exit(0); 190 | } 191 | } 192 | 193 | From 1.7 version onwards main() method is mandatory to start a program execution. Hence from 1.7 version onwards without writing main method it is impossible to print some statements to the console. 194 | 195 | ______________________________________________________ 196 | Static control flow in parent to child relation-ship 197 | ______________________________________________________ 198 | 199 | Whenever we are executing child class the following sequence of events will be executed automatically as part of static control flow. 200 | 201 | 1. Identification of static members from parent to child. step 1-11 202 | 2. Execution of static variable assignments and static blocks from parent to child. step 12-22 203 | 3. Execution of only child class main method. step 23-25 204 | 205 | 206 | class Base{ 207 | 1-->static int i = 10;-->12 208 | 209 | 2-->static{ 210 | m1(); -->13 211 | System.out.println("First static block"); -->15 212 | } 213 | 214 | 3-->public static void main(String[] args){ 215 | m1(); 216 | System.out.println("Main method"); 217 | } 218 | 219 | 4-->public static void m1(){ 220 | System.out.println(j);-->14 221 | } 222 | 223 | 5-->static int j = 20;-->16 224 | } 225 | 226 | class Derived extends Base{ 227 | 6-->static int x = 30;-->17 228 | 229 | 7-->static{ 230 | m2(); -->18 231 | System.out.println("Derived first static block");-->20 232 | } 233 | 234 | 8-->public static void main(String[] args){ 235 | m2();-->23 236 | System.out.println("Derived Main method");-->25 237 | } 238 | 239 | 9-->public static void m2(){ 240 | System.out.println(y);-->19,-->24 241 | } 242 | 243 | 10-->static{ 244 | System.out.println("Derived Second static block");-->21 245 | } 246 | 247 | 11-->static int y = 200;-->22 248 | } 249 | java Derived 250 | output 251 | 252 | 0 253 | base static block 254 | 0 255 | derived first static block 256 | derived second static block 257 | 258 | 200 259 | derived main 260 | 261 | java Base 262 | 263 | 0 264 | base static block 265 | 20 266 | base main 267 | 268 | Note: 269 | 270 | whenever we are loading child class automatically parent class will be loaded. But whenever we are loading parent class child class won't be loaded (because parent class members by default available to the child class where as child class members by default won't available to the parent). 271 | 272 | ______________________ 273 | Instance control flow 274 | ______________________ 275 | 276 | Whenever we are executing a java class first static control flow will be executed. In the static control flow if we are creating an object the following sequence of events will be executed as part of instance control flow 277 | 278 | 1. identification of instance members from top to bottom. Step 2 to 8 279 | 2. execution of instance variable assignments and instance blocks from top to bottom. Step 9 to 14 280 | 3. execution of constructor. Step 15 281 | 282 | class Test{ 283 | 3-->int n = 20;-->9 284 | 4-->{ 285 | m1();-->10 286 | System.out.println("First instance block");-->12 287 | } 288 | 5-->Test(){ 289 | System.out.println("constructor");-->15 290 | } 291 | 292 | 1-->public static void main(String[] args){ 293 | 2--> Test t = new Test(); //line 1 294 | System.out.println("Main"); 295 | } 296 | 6-->public void m1(){ 297 | System.out.println("Inside method "+j);-->11 298 | } 299 | 300 | 7-->{ 301 | System.out.println("Second static block");-->13 302 | } 303 | 8-->int j = 30;-->14 304 | } 305 | 306 | output: 307 | 308 | Inside method 0 309 | First instance block 310 | second instance block 311 | constructor 312 | Main 313 | 314 | 315 | if we comment line 1 then output is 316 | 317 | Main 318 | 319 | 320 | Note : static control flow is one time activity which will be performed at the time of class loading. 321 | But instance control flow is not one time activity and it will be performed for every object creation. 322 | object creation is most costly operation if there is no specific requirement then it is not recommended to create object. 323 | 324 | ______________________________________________________ 325 | Instance control flow in parent to child relationship 326 | ______________________________________________________ 327 | 328 | Whenever we are creating child class object the following sequence of events will be performed automatically as the part of instance control flow. 329 | 330 | 1. identification of instance members from parent to child. step 4 to 14 331 | 2. Execution of instance variable assignments and instance blocks only in parent class step 15 to 19 332 | 3. Execution of parent constructor. step 20 333 | 4. Execution of instance variable assignments and instance blocks in child class. step 21 to 26 334 | 5. Execution of child constructor step 27 335 | 336 | class Parent{ 337 | 4-->int i = 10;-->15 338 | 5-->{ 339 | m1();-->16 340 | System.out.println("Parent instance block");-->18 341 | } 342 | 6-->Parent(){ 343 | System.out.println("Parent constructor");-->20 344 | } 345 | 346 | 1-->public static void main(String[] args){ 347 | Parent P = new Parent(); //line 348 | System.out.println("Parent Main"); 349 | } 350 | 7-->public void m1(){ 351 | System.out.println("Inside method "+j);-->17 352 | } 353 | 354 | 8-->int j = 20;-->19 355 | } 356 | 357 | class Child extends Parent{ 358 | 9-->int x = 100;-->21 359 | 10-->{ 360 | m2();-->22 361 | System.out.println("child first instance block");-->24 362 | } 363 | 11-->Child(){ 364 | System.out.println("child constructor");-->27 365 | } 366 | 2-->public static void main(String[] args){ 367 | 3--> Child c = new Child(); 368 | System.out.println("child main");-->28 369 | } 370 | 371 | 12-->public void m2(){ 372 | System.out.println(y);-->23 373 | } 374 | 375 | 13-->{ 376 | System.out.println("child second instance block");-->25 377 | } 378 | 14-->int y = 200;-->26 379 | } 380 | 381 | output: 382 | 383 | 0 384 | Parent instance block 385 | parent constructor 386 | 387 | 0 388 | child first instance block 389 | child second instance block 390 | child constructor 391 | child main method 392 | 393 | _________________________________ 394 | instance and static control flow 395 | _________________________________ 396 | 397 | class Test{ 398 | { 399 | System.out.println("first instance block"); 400 | } 401 | static{ 402 | System.out.println("first static block"); 403 | } 404 | Test(){ 405 | 406 | System.out.println("Constructor"); 407 | } 408 | 409 | public static void main(String[] args){ 410 | Test t1 = new Test(); 411 | 412 | System.out.println("main"); 413 | Test t2 = new Test(); 414 | } 415 | static{ 416 | System.out.println("second static block"); 417 | } 418 | { 419 | System.out.println("second instance block"); 420 | } 421 | } 422 | 423 | first static block 424 | second static block 425 | first instance block 426 | second instance block 427 | constructor 428 | main 429 | first instance block 430 | second instance block 431 | constructor 432 | 433 | public class Initialization{ 434 | private static String m1(String msg){ 435 | System.out.println(msg); 436 | return msg; 437 | } 438 | public Initialization(){ 439 | m = m1("1"); 440 | } 441 | { 442 | m = m1("2"); 443 | } 444 | String m = m1("3"); 445 | 446 | public static void main(String[] arg){ 447 | Object o = new Initialization(); 448 | } 449 | } 450 | 451 | output: 452 | 453 | 2 454 | 3 455 | 1 456 | public class Inistialization{ 457 | private static String m1(String msg){ 458 | System.out.println(msg); 459 | return msg; 460 | } 461 | static String m = m1("1"); 462 | { 463 | m = m1("2"); 464 | } 465 | static{ 466 | m = m1("3"); 467 | } 468 | 469 | public static void main(String[] arg){ 470 | Object o = new Initialization(); 471 | } 472 | } 473 | 474 | output: 475 | 1 476 | 3 477 | 2 478 | 479 | 480 | Note ***: 481 | From static area we can't access instance members directly because while executing static area JVM may not identify instance members. 482 | 483 | class Test{ 484 | int x = 10; 485 | public static void main(String[] args){ 486 | Test t = new Test(); 487 | 488 | sopln(t.x); 489 | } 490 | } 491 | 492 | ************************************************************************************************ 493 | *in how many ways we can crate an object in java or in how many ways we can get object in java.* 494 | ************************************************************************************************ 495 | 1. By using new operation 496 | Test t = new Test(); 497 | 498 | 2. By using new instance method 499 | Test t = (Test) Class.forName("Test")newInstance(); 500 | 501 | 3. By using factory methods 502 | Runtime r = Runtime.getRuntime(); 503 | e.g dateFormat df = DateFormat.getInstance(); 504 | 505 | 4. By using clone() method. 506 | 507 | Test t1 = new Test(); 508 | Test t2 = (Test)t1.clone(); 509 | 510 | 5. By using deserilalization 511 | 512 | FileInputStream fis = new FileInputStream("abc.sar"); 513 | ObjectInputStream ois = new ObjectInputStream(fis); 514 | Dog d2 = (Dog)ois.readObject(); 515 | 516 | 517 | -------------------------------------------------------------------------------- /java class_durgasoft/enum: -------------------------------------------------------------------------------- 1 | Enumeration (enum) 2 | ______________________ 3 | 4 | if we want to represent a group of named constants then we should go for enum 5 | 6 | e.g enum month{ 7 | JAN, FEB, MARCH, ..., DEC; 8 | } 9 | 10 | enum Bear{ 11 | KF, KO, RC, FO;------------------> ';' is optional. 12 | } 13 | 14 | 15 | the main objective of enum is to define our own data types(enumerated data types). 16 | 17 | Enum concept introduced in 1.5 version when compared with old languages enum 'Java enum' is more powerful. 18 | 19 | _________________________________ 20 | Internal implementation of ENUM 21 | _________________________________ 22 | 23 | 1. every enum is implicitly(internally) implemented using class concept 24 | 2. every enum is always public static final. 25 | 3. Every enum concept represent an object of the type enum 26 | 27 | e.g. 28 | 29 | enum Beer{ 30 | RC, KF, RS; 31 | } 32 | 33 | also represents as. 34 | class Beer{ 35 | public static final Beer RC = new Beer(); 36 | public static final Beer KF = new Beer(); 37 | public static final Beer RS = new Beer(); 38 | } 39 | 40 | ____________________________ 41 | Enum declaration and usage. 42 | ____________________________ 43 | 44 | Every enum constant is always public static final and hence we can access enum constant by using enum name. 45 | 46 | enum Beer{ 47 | KF, RC, KO, FO; 48 | } 49 | 50 | class Test{ 51 | Beer b; 52 | public static void main(String[] args){ 53 | Beer b = Beer.RC; 54 | 55 | sopln(b); 56 | } 57 | } 58 | 59 | inside enum toString() method is implemented to return name of the constant. 60 | 61 | we can declare enum either within the class or outside a class but not inside a method. If we are trying to declare inside a method then we will get compile time error saying 62 | 63 | Enum types must not be local 64 | 65 | 66 | class X{ class X{ class X{ 67 | enum Y{ 68 | } public void m1(){ 69 | } 70 | enum Y{ enum Test{-------->CE : enum type must not be local. 71 | } T1, T2, T3; 72 | } } 73 | } 74 | } 75 | valid valid invalid 76 | 77 | if we declare anum outside of the class the applicable modifiers are 78 | 79 | 1. public 80 | 2. strictfp, 81 | 3. 82 | 83 | if we declare enum inside a class the applicable modifiers are 84 | 85 | 1. public 86 | 2. 87 | 3. strictfp 88 | + 89 | 4. private 90 | 5. protected 91 | 6. static. 92 | 93 | _________________________ 94 | enum vs switch 95 | _________________________ 96 | 97 | until 1.4 version the allowed argument types for the switch statement are 98 | 99 | 1. byte, 100 | 2. short 101 | 3. char 102 | 4. int 103 | 104 | but from 1.5 version onwards corresponding wrapper classes and enum types are allowed. 105 | 106 | from 1.7 version onwards String types also allowed. 107 | 108 | 1.4 1.5 1.7 109 | ______________________________ 110 | byte Byte 111 | short Short 112 | char Character String 113 | int Integer 114 | ___________________________________ 115 | 116 | hence from 1.5 version onwards we can pass enum type as argument to switch statement 117 | 118 | passing Enum to switch 119 | e.g 120 | enum Beer{ 121 | 122 | RC, RS, KO, MC; 123 | } 124 | public class EnumTest { 125 | 126 | public static void main(String[] args) { 127 | Beer b = Beer.RC; 128 | 129 | 130 | switch(b){ 131 | case RC: 132 | System.out.println("RoyalChallenger"); 133 | break; 134 | case RS: 135 | System.out.println("Raylstack"); 136 | break; 137 | case KO: 138 | System.out.println("Knockout"); 139 | break; 140 | case MC: 141 | System.out.println("Mackdownals"); 142 | break; 143 | default : 144 | System.out.println("default switch"); 145 | } 146 | } 147 | } 148 | 149 | output : 150 | 151 | RoyalChallenger 152 | 153 | if we pass enum type as argument to switch statement then every case label should be valid enum constant otherwise we will get compile time error. 154 | 155 | enum Beer{ 156 | 157 | RC, RS, KO, MC; 158 | } 159 | 160 | Beer b = Beer.RC; 161 | 162 | swithc(b){ 163 | case RC: 164 | break; 165 | case RS: 166 | break; 167 | case FO: 168 | break; 169 | case MC: 170 | break; 171 | case Testing : 172 | break;------------------->unqualified enumerations constant name required. 173 | } 174 | 175 | _________________________________ 176 | Enum vs Inheritance 177 | _________________________________ 178 | 179 | 1. Every enum is always direct child class of java.lang.enum and hence our enum can't extends any other enum (because java won't provide support for multiple inheritance). 180 | 181 | 2. Every enum is always final implicitly and hence for our enum we can't create child enum. 182 | 183 | because of above reasons we can conclude inheritance concept not applicable for enum explicitly. and we can't use extends keyword for enum. 184 | 185 | 186 | enum X{ enum X extends java.lang.Enum{ class X { enum X{ 187 | 188 | } } } } 189 | enum Y extends X{ class Y extends X{ 190 | enum Y extends X{ 191 | } 192 | } } 193 | CE : cannot inherit from final X 194 | //invalid //invalid //invalid CE : enum types are not extensible. 195 | 196 | 197 | any way an enum can implement any number of interfaces. 198 | 199 | e.g 200 | 201 | interface X 202 | 203 | enum Y implements X{ 204 | 205 | } 206 | 207 | conclusions java.lang.enum; 208 | _________________________________ 209 | 210 | 1. every enum in java is direct child class of java.lang.Enum. and hence this class acts as base class for all java enums. 211 | 212 | 2. it is an abstract class and it is direct child class of object. 213 | 214 | 3. it implements serializable and comparable interfaces. 215 | 216 | ____________ 217 | values() 218 | ____________ 219 | 220 | every enum implicitly contains values method to list-out all values present inside enum. 221 | 222 | e.g Beer[] b = Beer.values(); 223 | 224 | Note : values method not present in java.lang.Enum and object classes enum keywords implicitly provides this method. 225 | 226 | ________________ 227 | ordinal() 228 | ________________ 229 | 230 | inside enum order of constants is important and we can represent this order by using ordinal value. 231 | we can find ordinal value of enum constant by using ordinal method. 232 | 233 | public final int ordinal() 234 | 235 | ordinal value is 0 based like index of array. 236 | 237 | e.g 238 | 239 | enum{ 240 | KF, KO, RC, FO; 241 | } 242 | 243 | class Test{ 244 | public static void main(String[] args){ 245 | Beer[] b = Beer.ordinal(); 246 | 247 | for(Beer b1 : b){ 248 | System.out.println(b1 + "...." + b1.ordinal()); 249 | } 250 | } 251 | } 252 | 253 | output : 254 | ___________ 255 | 256 | KF....0 257 | KO....1 258 | RC....2 259 | FO....3 260 | 261 | 262 | ___________________________ 263 | Speciality of java enum 264 | ___________________________ 265 | 266 | in old languages enum we can take only constants but java enum in addition to constants we can take methods constructors normal variables etc. 267 | 268 | hence java enum is more powerfull than old languages enum. 269 | 270 | even inside java enum we can declare main() and we can run enum class directly from command prompt. 271 | 272 | e.g 273 | 274 | enum Fish{ 275 | STAR, GUPPI, GOLD; 276 | 277 | public static void main(String[] args){ 278 | System.out.println("ENUM MAIN METHOD"); 279 | } 280 | } 281 | 282 | 283 | 284 | javac Fish.java 285 | java Fish 286 | output: 287 | ENUM MAIN METHOD 288 | 289 | 290 | NOTE : In addition to constants if we are taking any extra member like a method then list of constants should be in the first line and should ends with ';' (semi-clone). 291 | 292 | e.g 293 | 294 | enum Fish{ 295 | STAR, GUPPY;---------------> ';' is mandatory 296 | 297 | public void m1(){ 298 | 299 | } 300 | } 301 | //valid 302 | 303 | 304 | enum Fish{ 305 | STAR, GUPPY---------------> ';' is mandatory 306 | 307 | public void m1(){ 308 | 309 | } 310 | } 311 | 312 | //invalid 313 | 314 | 315 | enum Fish{ 316 | 317 | public void m1(){ 318 | 319 | } 320 | 321 | STAR, GUPPY;---------------> list of constants should be in first line. 322 | } 323 | 324 | inside enum if we are taking any extra member like a method compulsory the first line should contains list of constants. atlist ';' (semicolon) 325 | 326 | e.g. 327 | 328 | 1. enum Fish{ 2. enum Fish{ 329 | public void m1(){ ; 330 | public void m1(){ 331 | } } 332 | } } 333 | 334 | invalid valid 335 | 336 | any way an empty enum is a valid java syntax. 337 | 338 | enum Fish{ 339 | 340 | } 341 | 342 | valid 343 | 344 | ___________________________________ 345 | an enum can contain constructor. 346 | ___________________________________ 347 | 348 | enum constructor will be executed separately for every enum constant at the time of enum class loading automatically. 349 | 350 | e.g 351 | 352 | enum Beer{ 353 | KF, KO, RC, FO; 354 | 355 | Beer(){ 356 | sopln("constructor"); 357 | } 358 | 359 | } 360 | 361 | class Test{ 362 | public static void main(String[] args){ 363 | 364 | Beer b = Beer.RC;----------------->line 1 365 | 366 | sopln("Hello"); 367 | } 368 | } 369 | 370 | output: 371 | 372 | constructor 373 | constructor 374 | constructor 375 | constructor 376 | 377 | Hello 378 | 379 | 380 | if we comment line 1 then output is 381 | 382 | Hello 383 | 384 | we can't create enum object directly and hence we can't invoke enum constructor directly. 385 | 386 | e.g 387 | 388 | Beer beer = new Beer(); //CE : enum type may not be instantiated. 389 | 390 | enum Beer{ 391 | KF(60), KO(70), RC(80), FO; 392 | int price; 393 | Beer(){ 394 | this.price = 65; 395 | } 396 | 397 | Beer(int price){ 398 | this.price = price; 399 | } 400 | public int getPrice(){ 401 | return this.price; 402 | } 403 | } 404 | 405 | class Test{ 406 | public static void main(String[] args){ 407 | 408 | Beer[] b = Beer.values(); 409 | for(Beer b1 : b){ 410 | sopln(b1 + "...." + b.setPrice()); 411 | } 412 | } 413 | } 414 | 415 | output: 416 | KF....60 417 | KO....70 418 | RC....80 419 | FO....65 420 | 421 | NOTE : KF means Beer KF = new Beer(); 422 | 423 | KF(70) means Beer KF = new Beer(70); 424 | 425 | Note : inside enum we can declare methods but should be concred methods only and we can't declare abstract methods. 426 | 427 | Case 1: 428 | _______ 429 | 430 | every enum constant represents an object of the type enum hence what ever methods we can apply on normal java objects, can be applicable on enum constants also. 431 | 432 | e.g 433 | 434 | Beer.KF.equals(Beer.RC); //valid 435 | Beer.KF.hashCode() > Beer.RC.hashCode(); //valid 436 | 437 | Beer.KF < Beer.RC; //invalid 438 | 439 | Beer.KF.ordinal() < Beer.RC.ordinal() //valid 440 | 441 | if we want to use any class or interface directly from outside package then the required import is normal import. 442 | if we want to access static members without class name then the required import is static import. 443 | 444 | e.g 445 | 446 | import static java.lang.Math.squreRoot; 447 | import java.lang.ArrayList; 448 | 449 | class Test{ 450 | public static void main(String[] args){ 451 | ArrayList al = new ArrayList(); 452 | 453 | sopln(squreRoot(4)); 454 | } 455 | } 456 | 457 | 458 | e.g | | 459 | | | 460 | package pack1; | package pack2; | package pack3; 461 | | | 462 | enum Fish{ | public class Test1{ | public class Test2{ 463 | STAR, GOLD, GUPPY; | public static void main(String[] args){ | public static void main(String[] args){ 464 | } | | 465 | | Fish f = Fish.GUPPY; | sopln(STAR); 466 | | sopln(f); | 467 | | } | } 468 | | } | } 469 | 470 | required import for above program is required import for above program is 471 | 472 | import pack1.Fish; import static pack1.Fish.STAR; 473 | or or 474 | import pack1.*; import static pack1.Fish.*; 475 | package pack4; 476 | 477 | public class Test3{ 478 | public static void main(String[] args){ 479 | Fish f = Fish.GUPPY; 480 | sopln(GOLD); 481 | } 482 | } 483 | 484 | required import for above program is 485 | 486 | import pack1.Fish; 487 | or 488 | import pack1.*; 489 | 490 | and 491 | 492 | import static pack1.Fish.*; 493 | 494 | or 495 | import static pack1.Fish.STAR; 496 | 497 | 498 | case 3 : 499 | __________ 500 | 501 | 502 | enum Color{ 503 | GREEN, RED, BLUE; 504 | public void info(){ 505 | sopln("universe color"); 506 | } 507 | } 508 | 509 | class Test{ 510 | public static void main(String[] args){ 511 | 512 | Color[] c = Color.values(); 513 | for(Color c1 : c){ 514 | sopln(c1 + "...." + c1.invo()); 515 | } 516 | } 517 | } 518 | 519 | 520 | output : 521 | 522 | universe color 523 | universe color 524 | universe color 525 | 526 | 527 | enum Color{ 528 | GREEN, RED{ 529 | public void info(){ 530 | sopln("Important color"); 531 | } 532 | }, BLUE; 533 | public void info(){ 534 | sopln("universe color"); 535 | } 536 | } 537 | 538 | class Test{ 539 | public static void main(String[] args){ 540 | 541 | Color[] c = Color.values(); 542 | for(Color c1 : c){ 543 | sopln(c1 + "...." + c1.invo()); 544 | } 545 | } 546 | } 547 | 548 | 549 | output : 550 | 551 | universe color 552 | important color 553 | universe color 554 | 555 | 556 | enum vs Enum vs Enumeration 557 | _______________________________ 558 | 559 | 1. enum : enum is keyword in java which can be used to define a group of named constants. 560 | 561 | 2. Enum is a class in java present in java.lang package. every enum in java should be direct child class of Enum class hence this class acts as base class for all java enums. 562 | 563 | 3. Enumeration is an interface present in java.util package. We can use enumeration object to get Objects one by one from the collection. 564 | 565 | 566 | 567 | 568 | -------------------------------------------------------------------------------- /java class_durgasoft/garbage collection: -------------------------------------------------------------------------------- 1 | 1. Introduction 2 | 2. The ways to make an object elegible for gc 3 | 3. The methods for requesting JVM to run garbage collection 4 | 4. finalization. 5 | 6 | _______________________________________________________________________________________ 7 | 8 | Introduction 9 | _______________ 10 | 11 | In old languages like c++, programmer is responsible to create new object and to destroy useless object usually programmer taking very much care while creating objects and neglecting destruction of useless objects because of his negligence at certain point for creation of new object sufficient memory may not be available (because total memory filed with useless objects only) and total application will be down with memory problems hence outOfMemoryError is very common problem in old languages like C++. 12 | 13 | But in Java programmer is responsible only for creation of objects and programmer is not responsible to destroy useless objects. Sun people provided one assistant to destroy useless objects this assistant is always running in the background(demon thread). And destroy useless objects. Just because of this assistant the chance of failing Java program with memory problems is very very low. This assistant is nothing but garbage collector. 14 | 15 | Hence the main objective of garbage collector is to destroy an useless objects. 16 | 17 | _____________________________________________ 18 | |How we can make an object eligible for GC | 19 | |_____________________________________________| 20 | |The ways to make an object eligible for GC | 21 | |_____________________________________________| 22 | 23 | even though programmer is not responsible to destroy useless objects it is highly recommended to make an object eligible for GC If it is no longer required. An object is said to be eligible for GC if and only if it doesn't contain any reference variable. 24 | 25 | The following are various ways to make an object eligible for GC. 26 | 27 | 28 | Nullifying the reference variable. 29 | _____________________________________ 30 | 31 | if an object no longer required then assign Null to all its reference variables then that object automatically eligible for garbage collection. 32 | This approach is nothing but nullifying the reference variable. 33 | 34 | e.g 35 | 36 | Student s1 = new Student(); 37 | Student s2 = new Student(); 38 | 39 | .---------------------> No object eligible for GC 40 | . 41 | . s1------> 42 | . 43 | . 44 | 45 | s1 = null; -----------------> one object eligible for GC 46 | . 47 | . 48 | . 49 | . 50 | s2 = null; -----------------> two objects eligible for GC 51 | 52 | 53 | 1. Re-assigning the reference variable if an object no longer required then re-assign its reference variable to some other object then old object by default eligible for garbage collection. 54 | 55 | e.g 56 | 57 | Student s1 = new Student(); 58 | Student s2 = new Student(); 59 | 60 | .---------------------> No object eligible for GC 61 | . 62 | . 63 | . 64 | . 65 | 66 | s1 = new Student(); -----------------> 1 object eligible for GC. 67 | . 68 | . 69 | . 70 | . 71 | s2 = s1; -----------------> s2 pointing to s1. two objects eligible for GC 72 | 73 | 74 | objects created inside a method 75 | _________________________________ 76 | 77 | The objects which are created inside a method are by-default eligible for GC once method completes. 78 | 79 | e.g 80 | 81 | class Test{ 82 | public static void main(String[] args){ 83 | m1(); 84 | ---------------------------------->2 objects eligible for GC. 85 | } 86 | public static void m1(){ 87 | Student s1 = new Student(); 88 | Student s2 = new Student(); 89 | } 90 | } 91 | 92 | e.g 2. 93 | class Test{ class Test{ 94 | public static void main(String[] args){ public static void main(String[] args){ 95 | Student s1 = m1();----------------->1 object eligible m1();----------------------------->two objects eligible 96 | } for GC. } for GC. 97 | 98 | public static Student m1(){ public static Student m1(){ 99 | Student s1 = new Student(); Student s1 = new Student(); 100 | Student s2 = new Student(); Student s2 = new Student(); 101 | return s1; return s1; 102 | } } 103 | } } 104 | 105 | e.g 3. 106 | 107 | class Test{ 108 | static Student s1; 109 | public static void main(String[] args){ 110 | m1(); 111 | ---------------------------------->1 objects eligible for GC. 112 | } 113 | public static void m1(){ 114 | s1 = new Student(); 115 | Student s2 = new Student(); 116 | } 117 | } 118 | 119 | ________________________________ 120 | Case 4: Island of Isolation 121 | ________________________________ 122 | 123 | class Test{ 124 | Test i; 125 | 126 | public static void main(String[] arg){ 127 | Test t1 = new Test(); 128 | Test t2 = new Test(); 129 | Test t3 = new Test(); 130 | --------------------------------| 131 | t1.i = t2;------------------------------|------>No object illegible for GC 132 | t2.i = t3;------------------------------| 133 | t3.i = t1;------------------------------| 134 | | 135 | t1 = null;------------------------------| 136 | t2 = null;------------------------------| 137 | t3 = null;------------------------------------> All objects are illegible for GC 138 | } 139 | } 140 | 141 | 142 | Note : 1. if an object doesn't contain any reference variable then it is illegible for garbage collection always. 143 | 2. even though object having references some times it is illegible for garbage collection.(if all references are internal references). 144 | 145 | e.g. Island of Isolation. 146 | 147 | ____________________________________________________________ 148 | The ways for requesting JVM to run garbage collector. 149 | ____________________________________________________________ 150 | 151 | Once we made an object illegible for GC it may not be destroyed immediately by garbage collector. Whenever JVM runs GC then only the objects will be destroyed. But when exactly JVM runs garbage collector we can't expect it is varied from JVM to JVM. 152 | 153 | Instead of waiting until JVM runs garbage collector we can request JVM to run garbage collector pro-grammatically but whether JVM accept our request or not there is no guaranty but most of the times JVM accepts our request. 154 | 155 | The following are two ways for request JVM to run garbage collector. 156 | 157 | 1. by using System class : System class contains a static method gc() for this purpose. 158 | _______________ 159 | |System.gc() | 160 | |_______________| 161 | 162 | 2. by using Runtime class : java application can communicate with JVM by using Runtime object. Runtime class present in java.lang package and it is a singleton class. We can create Runtime object by calling Runtime factory method called Runtime.getRuntime(). 163 | 164 | Runtime r = Runtime.getRuntime(); 165 | 166 | once we got Runtime object we can call the following methods on that object. 167 | 168 | 1. totalMemory(). 169 | 170 | it returns number of bytes of total memory present in the heap(i.e heap size). 171 | 172 | 2. freeMemory() : 173 | 174 | it returns number of bytes of free memory present it in the heap. 175 | 176 | 3. gc() : 177 | 178 | for requesting JVM to run garbage collection. 179 | 180 | 181 | import java.util.Date; 182 | 183 | public class TestRuntime { 184 | 185 | public static void main(String[] args) { 186 | Runtime runtime = Runtime.getRuntime(); 187 | 188 | System.out.println("total memory " + runtime.totalMemory()); 189 | System.out.println("free memory " + runtime.freeMemory()); 190 | for(int i = 0 ; i < 1000 ; i++){ 191 | 192 | Date d = new Date(); 193 | d = null; 194 | } 195 | System.out.println("free memory " + runtime.freeMemory()); 196 | System.out.println("free memory " + runtime.freeMemory()); 197 | runtime.gc(); 198 | System.out.println("free memory " + runtime.freeMemory()); 199 | } 200 | } 201 | 202 | 203 | output: 204 | 205 | total memory 5177344 206 | free memory 4945200 207 | free memory 4714464 208 | free memory 5059352 209 | 210 | Note : gc() present in System class is a static method where as gc() method present in Runtime class is instance method. 211 | 212 | Question : which of the following is valid way for requesting JVM to run garbage collector. 213 | 214 | 1. System.gc() //valid 215 | 2. runtime.gc(); //invalid 216 | 3. (new Runtime()).gc(); //invalid 217 | 4. Runtime.getRuntime().gc(); //valid 218 | 219 | 1. It is convenient to use System class gc() method when compared with Runtime class gc() method 220 | 2. with respect to performance it is highly recommended to use Runtime class gc() method when compared with System class gc() because System class gc() internally calls Runtime class gc() method. 221 | 222 | how System class gc() method implemented 223 | 224 | class System{ 225 | public static void gc(){ 226 | Runtime.getRuntime().gc(); 227 | } 228 | } 229 | 230 | 231 | _________________ 232 | Finalization 233 | _________________ 234 | 235 | Just before destroying an object garbage collector call finalize() method to perform cleanup activities. Once finalize() method completes automatically garbage collector destroys that object. 236 | 237 | finalize() method present in object class with the following declaration. 238 | 239 | protected void finalize() throws Throwable{} 240 | 241 | we can override finalize() method in our class to define our own cleanup activities. 242 | 243 | case 1 : 244 | 245 | just before destroying an object garbage collector calls finalize() on the object which is illegible for GC then the corresponding finalize() method will be executed. 246 | 247 | e.g if String object illegible for GC then String class finalize() method will be executed but not Test class finalize() method. 248 | 249 | e.g 250 | 251 | class Test{ 252 | public static void main(String[] args){ 253 | String s = new String(); 254 | s = null; 255 | System.gc(); 256 | sopln("end of main"); 257 | } 258 | 259 | @Override 260 | protected void finalize() throws Throwable { 261 | System.out.println("finalize() method call"); 262 | } 263 | } 264 | 265 | in the above example String object illegible for GC and hence String class finalize() method got executed which has empty implementation and hence the output is 266 | 267 | Output: 268 | end of main 269 | 270 | if we replace String object with Test object then Test class finalize() will be executed. 271 | 272 | in this case the output is 273 | 274 | end of main 275 | finalize() method call 276 | 277 | or 278 | 279 | finalize() method call 280 | end of main 281 | 282 | Case 2 : Based on our requirement we can call finalize() method explicitly then it will be executed just like a normal method call and object won't be destroyed. 283 | 284 | public class TestRuntime { 285 | 286 | public static void main(String[] args) { 287 | Runtime runtime = Runtime.getRuntime(); 288 | 289 | TestRuntime t = new TestRuntime(); 290 | t.finalize(); 291 | t.finalize(); 292 | t = null; 293 | System.out.println("end of main"); 294 | } 295 | 296 | @Override 297 | protected void finalize() throws Throwable { 298 | System.out.println("finalize method call"); 299 | } 300 | } 301 | 302 | 303 | in the above program finalize() method got executed three times in that two times explicitly by the programmer and one time by the garbage collector. In this case output is 304 | 305 | finalize method call 306 | finalize method call 307 | end of main 308 | finalize method call 309 | 310 | Note : if we are calling finalize method explicitly then it will be executed like a normal method call and object won't be destroyed. 311 | 312 | if garbage collector calls finalize() method then object will be destroyed. 313 | 314 | Note : init(), service() and destroy() methods are considered as life cycle methods of servlet. Just before destroying servlet object web container calls destroy() method to perform cleanup activities. But based on our requirement we can call destroy() method from init() and service() methods then destroy() method will be executed just like a normal method call and servlet object won't be destroyed. 315 | 316 | even though object illegible for GC multiple times but garbage collector calls finalize methods only once. 317 | 318 | class FinalizeDemo{ 319 | static FinzlizeDemo fd; 320 | 321 | public static void main(String[] args){ 322 | FinalizeDemo fd1 = new FinalizeDemo(); 323 | sopln(f.hashCode()); 324 | fd1 = null; 325 | System.gc(); 326 | Thread.sleep(5000); 327 | sopln(fd.hashCode()); 328 | s = null; 329 | System.gc(); 330 | Thread.sleep(10000); 331 | sopln("End of main"); 332 | } 333 | 334 | protected void finalize(){ 335 | sopln("Finalized method called"); 336 | s = this; 337 | } 338 | } 339 | 340 | output : 341 | 342 | 25724761 343 | Finalized method called 344 | 25724761 345 | End of main 346 | 347 | In the above program even though object illegible for GC two times but garbage collector calls finalize methods only once. 348 | 349 | we can't expect exact behavior of garbage collector it is varied from JVM to JVM hence for the following questions we can't answer exactly. 350 | 351 | 1. When exactly JVM runs garbage collector? 352 | 2. In which garbage collector identifies illegible objects? 353 | 3. In which order garbage collector destroys illegible objects? 354 | 4. Whether garbage collector destroys all illegible objects or not? 355 | 5. what is algorithm followed by garbage collector? 356 | etc. 357 | 358 | Note : whenever program runs with low memory then JVM runs garbage collector. But we can't expect exactly at what time 359 | 2. most of the garbage collectors follow stand algorithm 'mark and sweep' it doesn't mean every garbage collector follow the same algorithm. 360 | 361 | class FinalizeDemo{ 362 | static FinzlizeDemo fd; 363 | static int count = 0; 364 | public static void main(String[] args){ 365 | FinalizeDemo fd1 = new FinalizeDemo(); 366 | 367 | for(int i = 0; i<10; i++){-----------if we keep on increasing value of i from 10 to n at certain point memory problem will be 368 | fd1 = new FinalizeDemo(); raised then JVM runs garbage collector. garbage collector call finalize method on every 369 | fd1 = null; object separately and destroys that object. 370 | } 371 | 372 | } 373 | 374 | protected void finalize(){ 375 | sopln("Finalized method called" + ++count); 376 | s = this; 377 | } 378 | } 379 | 380 | ___________________ 381 | Memory leaks 382 | ___________________ 383 | 384 | The objects which are not using in our program and which are not illegible for GC such type of useless object are called memory leaks. 385 | In our program if memory leaks present then the program will be terminated by rising OutOfMemoryError. Hence if an object no longer required it is highly recommended to make that object illegible for GC. 386 | 387 | The following are various third party memory mgmt tools to identify memory leaks. 388 | 389 | HP OVO 390 | HP J METER 391 | JPROP 392 | PATROL 393 | IBM TIVOLI 394 | 395 | etc. (memory mgmt tools) 396 | -------------------------------------------------------------------------------- /java class_durgasoft/has - a relationship & overriding: -------------------------------------------------------------------------------- 1 | 1. Has a relationship is also known as composition or aggrigation. 2 | 2. there is no specific keyword to implement has a relation but most of the times we are depending on new keyword. 3 | 3. the main advantage of has a relationship is reusability of the code. 4 | e.g 5 | 6 | class Car{ 7 | Engine e = new Engine(); 8 | } 9 | 10 | Car has a engine reference. 11 | 12 | Difference between composition and aggrigation. 13 | 14 | Without existing container object if there is no chance of existing contained objects then container and contained objects are strongly associated and this strong association is nothing but composition. 15 | 16 | e.g 17 | university consist of several departments without existing university there is no chance of existing department hence university and department are stronly associated and this strong association is nothing but composition. 18 | 19 | suppose university contains several courses 20 | _________________ 21 | Aggrigation 22 | _________________ 23 | 24 | Without existing container object if there is chance of existing contained object then container and contained objects are weakly associated and this weak association is nothing but aggrigation. 25 | 26 | e.g 27 | Department consiste several professors without existing department there may be a chance of existing professor objects hence department and professor objects are weakly associated and this weak association is nothing but aggrigation. 28 | 29 | 30 | 31 | professor 1 32 | 33 | 34 | professor 1 35 | 36 | 37 | Department----------------------professor 1 38 | 39 | 40 | professor 1 41 | 42 | 43 | professor 1 44 | container objects contained objects 45 | 46 | 47 | Note : 1. in composition objects are strongly associated where as in aggrigation objects are weakly associated. 48 | 49 | 2. In composition container object holds directly contained objects where as in aggrigation container object holds just references of contained objects. 50 | 51 | 52 | Is-A vs Has-A 53 | ________________ 54 | 55 | Is-A 56 | 57 | 1. if we want total functionality of a class automatically then we should go for is-a relationship 58 | 59 | e.g complete functionality of Person class required for student class 60 | 61 | 2. if we want part of the functionality then we should go for has-a relationship. 62 | 63 | e.g test class contains 100 methods but within demo class I required only 1 or 2 methods then go for has-A relationship. 64 | 65 | ______________________ 66 | method signature 67 | ______________________ 68 | 69 | in java method signature consist of method names followed by argument types 70 | 71 | e.g public static int m1(int i, float f) 72 | 73 | m1(int,float) is method signature 74 | 75 | return type is not part of method signature in java 76 | 77 | compiler will use method signature to resolve method calls 78 | 79 | e.g 80 | 81 | class Test{ 82 | public void m1(int i){} 83 | 84 | public void m2(String s){} 85 | } 86 | 87 | Test t1 = new Test(); 88 | 89 | t1.m1(10); //valid 90 | t1.m2("Durga");//valid 91 | t1.m3(10.5);//invalid : CE: cannot find symbol : method m3(double) Location : Test 92 | 93 | 94 | within a class two methods with the same signature not allowed 95 | e.g 96 | 97 | class Test{ 98 | public void m1(int i){ 99 | 100 | } 101 | 102 | public int m1(int i){ //invalid : m1(int) is allready defined 103 | return temp 104 | } 105 | } 106 | 107 | _________________ 108 | overloading 109 | _________________ 110 | 111 | Two method are said to be overloaded if and only if both methods having same name but different argument types 112 | 113 | in 'C' language method overloading concept is not available hence we can't declare multiple methods with same name but different argument types if therer is change in argument type compulsary we should go for new method name which increases complexity of programming 114 | 115 | e.g 116 | //abs absolute value 117 | abs(int i) 118 | labs(long l) 119 | fabs(float f) 120 | 121 | but in java we can declare multiple methods with same name but different argument types such types of methods are called overloaded methods. 122 | 123 | abs(int i) | 124 | abs(long l) | overloaded methods 125 | abs(float f) | 126 | 127 | having overloading concept in java reduces complexity of programming 128 | 129 | 130 | class Test{ 131 | 132 | public void m1(){ 133 | sopln("no-arg"); 134 | } 135 | public void m1(int i){ 136 | sopln("int-arg"); 137 | } 138 | public void m1(double d){ 139 | sopln("double-arg"); 140 | } 141 | 142 | public static void main(String[] args){ 143 | t1.m1(); //m1() no arg method 144 | t1.m1(10); //m1(int) int arg method 145 | t1.m1(10.5); //m1(double) double arg method 146 | } 147 | } 148 | 149 | output : 150 | no-arg 151 | int-arg 152 | double-arg 153 | 154 | these are called as overloaded methods. 155 | 156 | **** in overloading method resolution always takes care by compiler based on reference type hence overloading is also considered as compile time polymorphism or static polymorphism or early binding 157 | 158 | _____________________________________________ 159 | Case 1 : Automatic promotion in overloading 160 | _____________________________________________ 161 | 162 | while resolving overloaded methods if exact match is not available then we won't get any compile time error immediately first it will promote argument to the next level and check whether matched method is available or not. 163 | 164 | if matched method is available then it will be considered and if matched method is not available then compiler promotes argument once again to the next level. This process will be continued until all possible promotions, still if matched method is not available then we will get compile time error. 165 | 166 | The following are all possible promotions in overloading 167 | 168 | byte---------------> short---->\ 169 | \ 170 | \ 171 | \ 172 | int--------->long---------->float----------->double 173 | / 174 | / 175 | / 176 | / 177 | char------------------------> 178 | 179 | this process automatic promotion in overloading. 180 | 181 | 182 | e.g 183 | 184 | class Test{ 185 | public void m1(){ 186 | System.out.println("No argument method"); 187 | } 188 | 189 | public void m1(int n){ 190 | System.out.println("int argument method"); 191 | } 192 | 193 | public void m1(float f){ 194 | System.out.println("float argument method"); 195 | } 196 | 197 | public static void main(String[] args){ 198 | Test t1 = new Test(); 199 | 200 | t1.m1(); //no argument method 201 | t1.m1(10); //int argument method 202 | t1.m1(10f); //float argument method 203 | t1.m1('a'); //int argument method 204 | t1.m1(10l); //float argument method 205 | t1.m1(10s); //CE: cannot find symbol location m1() class Test 206 | } 207 | } 208 | 209 | Case 2 : 210 | 211 | class Test{ 212 | public void m1(String str){ 213 | System.out.println("String version method"); 214 | } 215 | 216 | public void m1(Object obj){ 217 | System.out.println("Object version method"); 218 | } 219 | 220 | public static void main(String[] args){ 221 | Test t1 = new Test(); 222 | 223 | t1.m1(new Object()); //Object version method 224 | t1.m1("test"); //String version method 225 | t1.m1(null); //String version method 226 | } 227 | } 228 | 229 | 230 | 231 | Note : while resolving overloaded methods compiler will always gives preference for child type argument when compared with parent type argument 232 | 233 | Case 3 : 234 | 235 | class Test{ 236 | public void m1(String str){ 237 | System.out.println("String version method"); 238 | } 239 | 240 | public void m1(StringBugger obj){ 241 | System.out.println("StringBuffer version method"); 242 | } 243 | 244 | public static void main(String[] args){ 245 | Test t1 = new Test(); 246 | 247 | t1.m1("test"); //String version method 248 | t1.m1(new StringBuffer("test")); //StringBuffer version method 249 | 250 | 251 | t1.m1(null); //CE: reference to m1 is ambegious 252 | 253 | } 254 | } 255 | 256 | 257 | Case 4 : 258 | 259 | class Test{ 260 | public void m1(int i, float f){ 261 | System.out.println("int float version method"); 262 | } 263 | 264 | public void m1(float f, int i){ 265 | System.out.println("float int version method"); 266 | } 267 | 268 | public static void main(String[] args){ 269 | Test t1 = new Test(); 270 | 271 | t1.m1(10, 10.5f); //int float version method 272 | t1.m1(10.5f, 10); //float int version method 273 | 274 | 275 | t1.m1(10, 10); //CE: reference to m1 is ambegious 276 | t1.m1(10.5f, 10.5f); //CE: Can not find symbol method : m1(float, float) location : Test 277 | 278 | } 279 | } 280 | 281 | 282 | Case 5 : 283 | 284 | class Test{ 285 | public void m1(int i){ 286 | System.out.println("int version method"); 287 | } 288 | 289 | public void m1(int... i){ 290 | System.out.println("var-args version method"); 291 | } 292 | 293 | public static void main(String[] args){ 294 | Test t1 = new Test(); 295 | 296 | t1.m1(); //var-args version method 297 | t1.m1(10, 10); //var-args version method 298 | 299 | t1.m1(10); //int version method 300 | 301 | } 302 | } 303 | 304 | 305 | Note : in general var-arg method will get least priority i.e. if no other method matched then only var-arg method will get the chance. 306 | it is exactly same as default case inside switch. 307 | 308 | Case 6 : 309 | 310 | class Animal{ 311 | 312 | } 313 | 314 | class Monkey extends Animal{ 315 | 316 | } 317 | 318 | class Test{ 319 | 320 | public void m1(Animal a1){ 321 | System.out.println("Animal version"); 322 | } 323 | 324 | public void m1(Monkey m1){ 325 | System.out.println("Monkey version"); 326 | } 327 | 328 | public static void main(String... args){ 329 | Animal a = new Animal(); 330 | 331 | a.m1(a); //Animal version 332 | 333 | Monkey m = new Monkey(); 334 | m.m1(m); //Monkey version 335 | 336 | Animal a1 = new Monkey(); 337 | 338 | a1.m1(a1); //Animal version 339 | 340 | a1.m1((Monkey)a1); //Monkey version 341 | } 342 | 343 | } 344 | 345 | 346 | Note : in overloading method resolution always takes care by compiler based on reference type. 347 | in overloading runtime object won't play any role . 348 | 349 | 350 | -------------------------------------------------------------------------------- /java class_durgasoft/java Codding Standards: -------------------------------------------------------------------------------- 1 | _________________________ 2 | Java Codding Standards 3 | _________________________ 4 | 5 | Whenever we are writing java code it is highly recommanded to follow codding standards 6 | 7 | whenever we are writing any component it's name should reflect the purpose of that component(functionality) 8 | 9 | The main advantage of this approach is readability and maintainablity of the code will be improved. 10 | 11 | e.g 12 | 13 | worst kind of practice to write addition program 14 | 15 | class A{ 16 | 17 | int m1(int x1, int x2){ 18 | return x1 + x2; 19 | } 20 | } 21 | 22 | Good kind of practice to write addition program 23 | 24 | package com.test.scjp 25 | class Calculator{ 26 | int sum(int number1, int number 2){ 27 | return number1 + number2; 28 | } 29 | } 30 | 31 | coading standards for classes 32 | _______________________________ 33 | 34 | usually class names are nouns should start with upper case characters and if it contains multiple words every inner word should start with upper case character. 35 | 36 | e.g String 37 | StringBuffer 38 | Dog 39 | Account 40 | 41 | coding standards for interfaces 42 | __________________________________ 43 | 44 | usually interface names are adjectives 45 | should starts with upper case character and if it contains multiple words every inner word should starts with upper case character. 46 | 47 | e.g Runnable 48 | Compairable 49 | Seriazible 50 | 51 | coding standards for methods 52 | _______________________________ 53 | usually method names are either verbs or verb noun combination 54 | 55 | should starts with lower case alpha bet symbol and if it contains multiple words then every inner word should starts with upper case character(camel case convension) 56 | 57 | e.g print(); 58 | sleep(); 59 | run(); 60 | eat(); 61 | starts() 62 | these are verbs 63 | 64 | getName(); 65 | setSalary(); 66 | 67 | these are verb nown combinations 68 | 69 | 70 | _________________________________ 71 | Coding standards for variables 72 | _________________________________ 73 | 74 | usually variable names are nouns should starts with lowe case alphabet symbols and if it contains multiple words then every inner word should starts with upper case character 75 | 76 | Camel Case convension 77 | 78 | e.g name, age, mobileNumber etc 79 | 80 | codding standards for constants 81 | _________________________________ 82 | usually constants names are nouns should contain only upper case characers and if it contains multiple words then these words are seprated with underscore '_' symbol 83 | 84 | e.g 85 | MAX_VALUE 86 | MAX_PRIORITY 87 | NORM_PRIORITY 88 | PI 89 | 90 | Note : Usually we can declare constants with public static and final modifiers 91 | _________________________________ 92 | java bean codding standards 93 | _________________________________ 94 | 95 | a java bean is simple java class with private properties and public getter and setter methods 96 | 97 | e.g 98 | 99 | public class StudentBean{ 100 | private void name; 101 | public setName(String name){ 102 | this.name = name; 103 | } 104 | 105 | public String getName(){ 106 | return name; 107 | } 108 | } 109 | 110 | class name ends with ends with bean is not official convension from sun. 111 | __________________________ 112 | Syntax for setter method 113 | __________________________ 114 | 115 | it should be public method the return type should be void method name should be prefixed with set. 116 | it should take some argument i.e it should not be no-argument method. 117 | 118 | syntax for getter method 119 | _________________________ 120 | 121 | It should be public method the return type should not be void method name should prefixed with get the it should not take any argument. 122 | 123 | * Note : for boolean properties getter method name can be prefixed with either get or is but recommanded to use is. 124 | 125 | e.g 126 | 127 | private boolean empty; 128 | 129 | public boolean getEmpty(){ 130 | return empty; 131 | } 132 | 133 | or 134 | 135 | public boolean isEmpty(){ 136 | return empty; 137 | } 138 | 139 | coading standards for listener 140 | _________________________________ 141 | Case 1 : to register a listener 142 | 143 | method name should be prefixed with add 144 | 145 | e.g 146 | public void addMyActionListener(myActionListener l) // valid 147 | 148 | public void registerMyActionListener(myActionListener l)// invalid 149 | 150 | public void addMyActionListener(ActionListener l)// invalid 151 | 152 | To unregister method name should prefixed with remove 153 | 154 | public void removeMyActionListener(myActionListener l) // valid 155 | 156 | public void unregisterMyActionListener(myActionListener l) // invalid 157 | 158 | public void removeMyActionListener(ActionListener l)//invalid 159 | 160 | public void deleteMyActionListener(MyActionListener l)//invalid 161 | -------------------------------------------------------------------------------- /java class_durgasoft/java_lang package: -------------------------------------------------------------------------------- 1 | java.lang package 2 | 3 | 1. Introduction 4 | 2. Object Class 5 | 3. String class 6 | 4. StringBuffer class 7 | 5. StringBuilder class 8 | 6. Wrapper classes 9 | 7. AutoBoxing AutoUnboxing. 10 | 11 | ------------------------------------ 12 | ____________________ 13 | Introduction 14 | ____________________ 15 | 16 | For writing any java program whether it is simple or complex the most commonly required classes and interfaces are grouped into a separate package which is nothing but java.lang package 17 | 18 | we are not required to import java.lang package explicitly because all classes and interfaces present in Lang package by default available to every java program ---- 19 | 20 | __________________ 21 | java.lang.Object 22 | __________________ 23 | 24 | the most commonly required method are defined in a separate class which is nothing but object class for every java class whether it is predefined class or customized class. 25 | 26 | Every class in java is child class of object either directly or indirectly so that object class methods by default available to every java class. 27 | 28 | Hence Object class is considered as root of all java classes. 29 | 30 | Note : if our class doesn't extend any other class then only our class is the direct child class of object. 31 | 32 | e.g class A{ 33 | 34 | } 35 | 36 | A is child of object 37 | 38 | if our class extends any other class then our class is indirect child class of object 39 | 40 | e.g 41 | 42 | class A extends B{ 43 | 44 | } 45 | 46 | A is child of Object //invalid 47 | 48 | A is child of B and B is child of Object // valid 49 | 50 | Conclusion 51 | ______________ 52 | 53 | Either directly or indirectly java won't provide support for multiple inheritance with respect to classes. 54 | 55 | Object class defines the following 11 methods 56 | 57 | public String toString(); 58 | public native int hashCode(); 59 | public boolean equals(); 60 | protected native Object clone() throws CloneNotSupportedException 61 | protected void finalize() throws Throwable 62 | public void finalize() throws InterruptedException 63 | public final void wait() throws InterruptedException 64 | public final native void wait(long milliseconds) throws InterruptedException 65 | public final void wait(long milliseconds, int nanoSeconds) throws InterruptedException 66 | public final void notify(); 67 | public final void notifyAll(); 68 | 69 | These are 11 methods present inside object class 70 | 71 | Strictly speaking object class contains 12 methods the extra methods is registerNatives(). 72 | 73 | private static native void registerNatives(); 74 | 75 | this method internally required for object class and not available to the child classes hence we are not required to consider this method 76 | 77 | ________________________ 78 | 1. toString() method 79 | ________________________ 80 | 81 | we can use toString() method to get string representation of an object. 82 | 83 | String s = obj.toString(); 84 | 85 | whenever we are trying to print object reference internally toString() method will be called. 86 | 87 | e.g Student s = new Student(); 88 | 89 | sopln(s); //(sopln(s.toString())) 90 | 91 | if our class doesn't contain toString() method then object class toString() method will be executed. 92 | e.g 93 | class Student{ 94 | String name; 95 | int rollNo; 96 | 97 | Student(String name, int rollNo){ 98 | this.name = name; 99 | this.rollNo = rollNo; 100 | } 101 | 102 | public static void main(String[] args){ 103 | Student s1 = new Student("ravi", 101); 104 | Student s2 = new Student("teja", 102); 105 | 106 | sopln(s1); //Student@6545523 107 | sopln(s1.toString()); //Student@6545523 108 | sopln(s2.toString()); //Student@654412 109 | } 110 | } 111 | 112 | In the above example object class toString() method got executed which is implemented as follows 113 | 114 | public String toString(){ 115 | return getClass().getName()+"@"+Integer.toHexString(hashCode()); 116 | } 117 | 118 | classname@hashcode in hexadecimal form. 119 | 120 | based on our requirement we can override toString() method to provide our own String representation. 121 | 122 | e.g. Whenever we are trying to print student object reference to print his name and roll no we have to override toString() method as follows. 123 | 124 | public String toString(){ 125 | return name + "..." + rollNo; 126 | } 127 | 128 | return "this is student with name :" + name + " Roll no :" + rollno; 129 | 130 | in all wrapper classes, in all collection classes String class, StringBuffer and StringBuilder class toString() method is overridden for meaning full String representation hence it is highly recommended to override toString() method in our class also 131 | 132 | e.g 133 | 134 | class Test{ 135 | public String toString(){ 136 | return "Test"; 137 | } 138 | 139 | public static void main(String[] args){ 140 | String s = new String("Test"); 141 | System.out.println(s); 142 | Integer i = new Integer(20); 143 | System.out.println(i); 144 | ArrayList al = new ArrayList(); 145 | al.add("ravi"); 146 | al.add("shiva"); 147 | System.out.println(al); 148 | Test t = new Test(); 149 | System.out.println(t); 150 | } 151 | } 152 | 153 | output : 154 | 155 | Test 156 | 20 157 | [ravi, shiva] 158 | Test 159 | 160 | ____________ 161 | HashCode() 162 | ____________ 163 | 164 | for every object a unique number generated by JVM which is nothing but hashCode(); 165 | 166 | hashCode() won't represents address of object. JVM will use hashCode while saving objects into hashing related data structures. Like hash table hash map, hash Set etc. The main advantage of saving objects based on hashCode() is search operation will become easy(the most powerfull search algorithm upto today is hashing.) 167 | 168 | if you are giving the chance to object class hashCode() method it will generates hash code based on address of the object. It doesn't mean hashCode() represents address of the object. Based on our requirement we can override hashCode() method in our class. to generates our own hashCode(). 169 | 170 | overriding hash code method is said to be proper if and only if for every object we have to generate a unique number as hashCode(). 171 | 172 | class Student{ 173 | . 174 | . 175 | . 176 | public int hashCode(){------------>//invalid way or improper way 177 | return 100; 178 | } 179 | } 180 | 181 | this is improper way of overriding hashCode() method. because for all student objects we are generating same number as hashCode() 182 | 183 | class Student{ 184 | . 185 | . 186 | . 187 | public int hashCode(){------------>//valid way or proper way 188 | return rollNo; 189 | } 190 | } 191 | 192 | This is proper way of overriding hashCode() method because we are generating a different number as hashCode() for every object. 193 | 194 | ____________________________ 195 | toString() vs hashCode() 196 | ____________________________ 197 | 198 | if we are giving chance to object Class toString() method it will internally calls hashCode() method. if we are overriding toString() method then our toString() method may not call hashCode() method. 199 | 200 | e.g 1 201 | 202 | class Test{ 203 | int i; 204 | Test(int i){ 205 | this.i = i; 206 | } 207 | 208 | public static void main(String[] args){ 209 | Test t1 = new Test(10); 210 | Test t2 = new Test(100); 211 | sopln(t1); 212 | sopln(t2); 213 | } 214 | } 215 | 216 | output : 217 | 218 | Test@654654 219 | Test@654842 220 | 221 | 222 | class Test{ 223 | int i; 224 | Test(int i){ 225 | this.i = i; 226 | } 227 | public int hashCode(){ 228 | return i; 229 | } 230 | public static void main(String[] args){ 231 | Test t1 = new Test(10); 232 | Test t2 = new Test(100); 233 | sopln(t1); 234 | sopln(t2); 235 | } 236 | } 237 | 238 | output : 239 | 240 | Test@10 241 | Test@100 242 | class Test{ 243 | int i; 244 | Test(int i){ 245 | this.i = i; 246 | } 247 | public int hashCode(){ 248 | return i; 249 | } 250 | 251 | public String toString(){ 252 | 253 | return String.valueOf(i); 254 | } 255 | public static void main(String[] args){ 256 | Test t1 = new Test(10); 257 | Test t2 = new Test(100); 258 | sopln(t1); 259 | sopln(t2); 260 | } 261 | } 262 | 263 | output : 264 | 265 | 10 266 | 100 267 | 268 | _________________ 269 | equals() method 270 | _________________ 271 | we can use equals method to check equality of two objects. 272 | 273 | e.g obj1.equals(obj2); 274 | 275 | if our class doesn't contain equals method then object class equals method will be executed. 276 | 277 | class Test{ 278 | 279 | String name; 280 | int rollNo; 281 | 282 | Test(String name, int rollno){ 283 | this.name = name; 284 | this.rollNo = rollno; 285 | } 286 | public static void main(String[] args){ 287 | 288 | Test t1 = new Test("durga",101); 289 | Test t2 = new Test("ravi",101); 290 | Test t3 = new Test("durga",101); 291 | Test t4 = t1; 292 | 293 | sopln(t1.equals(t2)); 294 | sopln(t1.equals(t3)); 295 | sopln(t1.equals(t4)); 296 | 297 | } 298 | } 299 | 300 | output: 301 | 302 | false 303 | false 304 | true 305 | 306 | in the above example object class equals method got executed which is ment for reference compression(address compression) i.e if two references pointing to the same object then only that equals method returns true. 307 | 308 | based on our requirement we can override equals() method for content compression. 309 | 310 | while overriding equals method for content compression we have to take care about the following. 311 | 312 | what is the meaning of equality (i.e whether we have to check only name or only rollNumbers or both). 313 | 314 | if we are passing different type of object our equals method should not rise ClassCastException i.e we have to handle ClassCastException to return false. 315 | 316 | if we are passing null argument then our equals method should not rise NullPointerException. i.e we have to handle NullPointerException to return false. 317 | 318 | The following is a proper way of overriding equals() method for student class content compression. 319 | 320 | public boolean equals(Object obj){ 321 | try{ 322 | String name1 = this.name; 323 | int rollNo1 = this.rollNo; 324 | 325 | Student s = (Student) obj; //RE : ClassCastException 326 | 327 | String name2 = s.name();----|----------->//RE : NullPointerException 328 | int rollno2 = s.rollno;-----| 329 | 330 | if(name1.equals(name2) && rollNo1 == rollNo2){ 331 | reurn true; 332 | } 333 | return false; 334 | }catch(ClassCastException e){ 335 | return false; 336 | }catch(NullPointerException e){ 337 | return false; 338 | } 339 | } 340 | 341 | Student s1 = new Student("durga", 101); 342 | Student s2 = new Student("ravi", 101); 343 | Student s3 = new Student("durga", 101); 344 | Student s4 = s1; 345 | 346 | sopln(s1.equals(s2)); //false 347 | sopln(s1.equals(s3)); //true 348 | sopln(s1.equals(s4)); //true 349 | 350 | ______________________________________ 351 | Simplified version of equals() method 352 | ______________________________________ 353 | 354 | public boolean equals(Object obj){ 355 | try{ 356 | 357 | Student s = (Student) obj; //RE : ClassCastException 358 | 359 | if(this.name.equals(s.name2) && this.rollNo == s.rollNo2){ 360 | reurn true; 361 | } 362 | return false; 363 | }catch(ClassCastException e){ 364 | return false; 365 | }catch(NullPointerException e){ 366 | return false; 367 | } 368 | } 369 | ___________________________________________ 370 | more simplified version of equals() method 371 | ___________________________________________ 372 | 373 | public boolean equals(Object obj){ 374 | 375 | if(obj instanceof Student){ 376 | 377 | Student s = (Student) obj; //RE : ClassCastException 378 | 379 | if(this.name.equals(s.name2) && this.rollNo == s.rollNo2){ 380 | reurn true; 381 | } 382 | return false; 383 | } 384 | return false; 385 | 386 | } 387 | 388 | Note : to make above equals() method more efficient we have to write the following code at the begging inside equals method 389 | 390 | if(obj == this){ 391 | return true; 392 | } 393 | 394 | according to this if both references pointing to the same object then without performing any comparison .equals() method returns true directly. 395 | 396 | 397 | 398 | String s1 = new String("Durga"); StringBuffer sb1 = new StringBuffer("Durga"); 399 | String s2 = new String("Durga"); StringBuffer sb2 = new StringBuffer("Durga"); 400 | 401 | sopln(s1 == s2); //false sopln(sb1 == sb2); //false 402 | sopln(s1.equals(s2)); //true sopln(sb1 == sb2); //false 403 | 404 | 405 | in String class .equals() method in StringBuffer .equals() method is not overridden 406 | is overridden for content comparison, for content comparison hence if objects are equals 407 | even though objects are different if .equals() method returns false even though content is same. 408 | content is same then .equals() method 409 | returns true. 410 | 411 | __________________ 412 | getClass() method 413 | __________________ 414 | 415 | we can use getClass() method to get run time class definition of an object. 416 | 417 | public final Class getClass(); 418 | 419 | by using this 'Class' class object we can access class level properties like fully qualified name of the class. 420 | Methods information 421 | Constructors information. 422 | etc. 423 | 424 | import java.lang.reflect.Method; 425 | 426 | public class Test { 427 | public static void main(String[] args) { 428 | int count = 0; 429 | Object o = new String("Durga"); 430 | 431 | Class c = o.getClass(); 432 | 433 | System.out.println("Fully Qualified name of class: " + c.getName()); 434 | Method[] m = c.getDeclaredMethods(); 435 | System.out.println("Method information : "); 436 | for (Method methods : m) { 437 | System.out.println(methods.getName()); 438 | count++; 439 | } 440 | System.out.println("No of methods are : " + count); 441 | } 442 | } 443 | 444 | e.g 2. 445 | 446 | To display database vendor specific connection interface implemented class name 447 | 448 | Connection con = DriverManager.getConnection(...); 449 | sopln(con.getClass().getName()); 450 | 451 | _______ 452 | Note : 453 | _______ 454 | 455 | After loading every .class file JVM will create an object of the type java.lang.Class in the heap area. 456 | 457 | Programmer can use this class object to get class level information. 458 | 459 | we can use getClass() method very frequently in reflections. 460 | 461 | ___________ 462 | finalize() 463 | ___________ 464 | 465 | just before destroying an object garbage collector calls finalize method to perform cleanup activities. once finalize method complete automatically garbage collector destroys that object 466 | 467 | wait(), notify(), notifyAll() 468 | 469 | we can use these methods for inter thread communication 470 | 471 | the thread which is expecting updation, it is responsible to call wait() then immediately the thread enter into waiting state. 472 | 473 | The thread which is responsible to perform updation, after performing updation the thread can call notify method. 474 | 475 | The waiting thread will get that notification and continue its execution with those updates. 476 | 477 | 478 | -------------------------------------------------------------------------------- /java class_durgasoft/language fundamentals - part 1: -------------------------------------------------------------------------------- 1 | Core Java with OCJP/SCJP : Language Fundamentals Part-1 || Java Identifiers and Reserved Words : 2 | ________________________________ 3 | java Lauange fundamentals : 4 | ________________________________ 5 | 6 | 1. Identifiers 7 | 2. reserves 8 | 3. datatypes 9 | 4. literals 10 | 5. arrays 11 | 6. types of variables 12 | 7. varargs methods 13 | 8. main method 14 | 9. Command line arguments 15 | 10. Java Coding standards 16 | 17 | ______________ 18 | Identifier : 19 | ______________ 20 | A name in java program is called identifier which can be used for identification purpose, it can be method name or variable name class name or lable name. 21 | 22 | e.g : 23 | 24 | class Test{ 25 | 26 | public static void main(String[] args){ 27 | int x = 10; 28 | } 29 | } 30 | 31 | Identifiers in above examples : 32 | 33 | 1. Test, 2. main, 3. args, 4. String, 5. x 34 | 35 | _______________________________________ 36 | Rules for Defining java identifiers 37 | _______________________________________ 38 | 1. only allowed character in java identifiers are. 39 | 40 | a to z, A to Z, 0 to 9, '$', '_' 41 | 42 | if we are using any other character we will get compile time error. 43 | 44 | e.g total_number //is valid 45 | 46 | total# //is invalid 47 | 48 | 2. identifiers can't start with digit. 49 | 50 | total123 //is valid 51 | 123total //is invalid 52 | 53 | 3. java identifiers are case sensitive offcourse java language itself is treated as case sensitive programming language. 54 | 55 | e.g class Test{ 56 | int number = 10; 57 | int Number = 20; 58 | int NUMBER = 30; 59 | } 60 | 61 | 62 | we can differentiate with case 63 | 64 | 4. there is no length limit for java identifiers but it is not recommanded to take too lengthy identifiers 65 | 66 | 5. we can't use reserved words as identifiers 67 | 68 | e.g int x = 10; is valid 69 | int if = 20; is invalid(CE : if is reserved word). 70 | 71 | 6. all predefined java class name and interface name we can use as identifiers. 72 | 73 | e.g class Test{ 74 | public static void main(String[] arg){ 75 | int String = 10; 76 | int runnable = 999; 77 | 78 | System.out.println(String); 79 | System.out.println(runnable); 80 | } 81 | } 82 | 83 | Output : 84 | 85 | 10 86 | 999 87 | 88 | even though it is valid but it is not a good programming practic because it reduces redability and creates confusion. 89 | 90 | total_number //valid 91 | total# //invalid 92 | 123total //invalid 93 | total123 //valid 94 | ca$h //valid 95 | _$_$_$_ //valid 96 | all@hash //invalid 97 | java2share //valid 98 | Integer //valid 99 | Int //valid 100 | int //invalid 101 | 102 | __________________________ 103 | Reserved words in java: 104 | __________________________ 105 | 106 | 1. in java some words are reserved to represent some meaning or functionality such type of words are called reserved words. 107 | 108 | 109 | reserved words(53) 110 | / \ 111 | / \ 112 | / \ 113 | / \ 114 | / \ 115 | / \ 116 | 117 | keyword(50) reserved litrals(3) 118 | / \ true 119 | / \ false 120 | / \ null 121 | / \ 122 | / \ 123 | / \ 124 | used unused 125 | keywords(48) keywords(2) 126 | 127 | 128 | 129 | 1. key words for data types 130 | 131 | byte, short, int ,long, float, double, char, boolean 132 | 133 | 2. keywords for flow control 134 | if, else, switch, case, default, do, while, for, break, continue, return 135 | 136 | 3. keywords for modifiers 137 | 138 | public, private, protected, static, final, abstract, synchronized, native, strictfp(1.2), transient, volatile(,default). 139 | 140 | 4. keywords for exception handling 141 | 142 | try, catch, finally, throws, throw, assert(1.4). 143 | 144 | 5. class related keywords. 145 | 146 | class, interface, extends, implements, package, import, 147 | 148 | 6. object related keywords 149 | 150 | new, instanceof, super, this, 151 | 152 | 7. void return type keyword 153 | 154 | in java return type is manidetory, if a method won't return anything then we have to declare that method with void return type. 155 | 156 | but in 'C' language return type is optional and default return type is int. 157 | 158 | 8. Unused keywords 159 | 160 | a. goto 161 | 162 | usage of goto create several problems in old languages and hence sun people bane this keyword in java, 163 | 164 | b. const 165 | 166 | use final instead of const. 167 | 168 | Note : goto and const are unused keywords and if we are trying to use we will get compile time error. 169 | 170 | 9. Reserved literals 171 | 172 | true, false values for boolean datatypes 173 | 174 | null is default value for object reference. 175 | 176 | 10. enum(1.5) keyword 177 | 178 | we can use enum to define a group of named constants. 179 | 180 | e.g enum Month{ 181 | Jan, Feb, ...., Dec; 182 | } 183 | 184 | enum beer{ 185 | KF, KO, RC, FO; 186 | } 187 | 188 | conclusions 189 | 190 | 1. All 53 reserved words in java contains only lower case alpha bet symbols. 191 | 2. in java we have only new keyword and there is no delete keyword because 192 | distruction of useless objects is responsibility of garbage collector 193 | 194 | 3. The follwoing are new keywords in java. 195 | 196 | 1. strictfp(1.2) 197 | 2. assert(1.4) 198 | 3. enum(1.5) 199 | 200 | 4. strictfp but not strictFp 201 | instanceof but not instanceOf 202 | synchronized but not synchronize 203 | extends but not extend 204 | implements but not implements 205 | import but not imports 206 | const but not constant 207 | 208 | 209 | Q. Which of the follwing list contains only java reserved words. 210 | 211 | 1. new, delete. 212 | 2. goto, constant. 213 | 3. break, continue, return, exit. 214 | 4. final, finally, finalize. 215 | 5. throw, throws, thrown. 216 | 6. notify, notifyAll. 217 | 7. implements, extends, imports. 218 | 8. sizeOf, instanceof. 219 | 9. instanceOf, strictFp. 220 | 10. byte, short, Int. 221 | 11. None of above. 222 | 223 | 224 | Q. Which of following are java reserved words? 225 | 226 | 1. public 227 | 2. static 228 | 3. void 229 | 4. main 230 | 5. string 231 | 6. args. 232 | -------------------------------------------------------------------------------- /java class_durgasoft/language fundamentals- datatypes: -------------------------------------------------------------------------------- 1 | DataTypes in java 2 | __________________________________________________ 3 | 4 | 1. in java every variable and every expression has some type. 5 | 2. each and every data type is clearly defined. 6 | 3. every assignment should be checked by compiler for type compatibility. 7 | 4. because of above resons we can conclude java language is strongly typed programming language. 8 | 5. java is not considered as pure object oriented programming language because several oop features are not satisfied by java(like operator overloading and multiple inheritance etc.). 9 | 6. more over we are depending on premitive datatypes which are non objects. 10 | 11 | 12 | 13 | primitive data types 14 | /\ 15 | / \ 16 | / \ 17 | / \ 18 | / \ 19 | / \ 20 | 21 | Numeric DataType Non Numeric DataType 22 | 23 | / \ a. char 24 | / \ b. boolean 25 | / \ 26 | / \ 27 | / \ 28 | Integral DataType Floating point 29 | data type 30 | a. byte a. float 31 | b. short b. double 32 | c. int 33 | d. long 34 | 35 | Except boolean and char remaining data types are considered as signed data types because we can represent both positive and negative numbers. 36 | 37 | 38 | byte DataType: 39 | 40 | Byte size 1byte(8 bits) 41 | max value +127 42 | Min Value -128 43 | 44 | Range -128 to +127 45 | 46 | _________________________________________________________________ 47 | Size | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 48 | | | | | | | | | 49 | __________________________________________________________________ 50 | Signed 6 5 4 3 2 1 0 51 | bit 2 2 2 2 2 2 2 52 | 53 | Signed bit represent +ive or -ive value 54 | 55 | 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127 56 | 57 | 58 | the most significant beat access signed bit 59 | 0 means positive number, 1 means negative number. Positive number will be represented directly in memory where as negative numbers will be represented in 2's complement form 60 | 61 | 62 | byte b = 10; //valid 63 | byte b = 127; //valid 64 | byte b = 128; //invalid 65 | Compile Error : possible loss of precision found: int required: byte 66 | byte b = 10.5 //invalid 67 | Compile Error : possible loss of precision found: double required: byte 68 | 69 | byte b = true 70 | Compile Error : incompatible type 71 | found : boolean 72 | required : byte 73 | 74 | byte is best choice if we want to handle data in terms of stream either from file or from the network(file supported form or network supported form is byte). 75 | 76 | short : this is most rearly used datatype in java 77 | 78 | size = 2 bytes(16 bits) 79 | 15 15 80 | range : -2 to 2 - 1 81 | [-32768 to 32767] 82 | 83 | short s = 32767; valid 84 | short s = 32768; CE : PLP found : int required : short 85 | short s = 10.5; CE : PLP found : double required : short 86 | short s = true; CE: incompatable types found boolean required:short 87 | 88 | short data type is best sutaible for 16- bit processor like 8085 but these processers are completely out dated and hence corresponding short data type is also outdated data type. 89 | 90 | _______________________ 91 | int data type : 92 | _______________________ 93 | 94 | the most commonly used data type in java is "int" 95 | size - 4bytes (32 bits) 96 | 32 32 97 | range -2 to 2 -1 98 | 99 | [-2147483648 to 2147483647] 100 | 101 | e.g int x = 2147483647; //valid 102 | int x = 21474848; //invalid CE : Integer number too large 103 | int x = 21474848l; //invalid CE : Possible loss of precision. found : Long required : int. 104 | int x = true; //incompaitable type 105 | found : boolean 106 | required : int 107 | ___________________ 108 | long data type: 109 | ___________________ 110 | 111 | Some time int may not enough to hold big values then we should go for long type. 112 | e.g 1. The amount of distance traveled by light in 1000 days, to hold this value int may not enough we should go for long data type 113 | 114 | e.g 1.long l = 126000 * 60 * 60 * 24 * 1000; miles 115 | e.g 2. the number of characters present in a big file may excid int range hence the return type of length method is long but not int. 116 | File f = new File(); 117 | long l = f.length(); 118 | 119 | Size : 8 bytes(64bits) 120 | 63 63 121 | range : -2 to 2 -1 122 | 123 | Note : all the above data types(byte, short, int, long) ment for representing can be used to represent integral value if we want to represent 124 | floating point values then we should go for floating point datatypes. 125 | ______________________________ 126 | Floating point data types : 127 | ______________________________ 128 | _______________________________________________ 129 | float | double 130 | ____________________|__________________________ 131 | 1. 5 to 6 | 1. 14 to 15 132 | 2. Single Precision | 2. Double precision 133 | 3. Size 4 bytes | 3. Size 8 bytes 134 | 4. Range | 4. Range 135 | -3.4e38 to 3.4e38 | -1.7e308 to 1.7e308 136 | ____________________|___________________________ 137 | 138 | ______________________ 139 | Boolean data type : 140 | ______________________ 141 | 142 | Size : NA[VM dependent] 143 | Range : NA [but allowed values are true or false]. 144 | 145 | boolean b = true; valid 146 | 147 | boolean b = 0; CE : can not find symbol 148 | symbol : variable True 149 | location : class Test 150 | 151 | boolean b = "True"; CE : incompatable types 152 | found : java.lang.String 153 | required : boolena 154 | 155 | 156 | int x = 0; 157 | 158 | if(x){ 159 | sop("Hello"); 160 | }else { 161 | sop("hi"); 162 | } 163 | 164 | error : incompatable types found: int required boolean 165 | 166 | while(1){sop("hello");} 167 | 168 | error : incompatable types found: int required boolean 169 | 170 | char data type : 171 | ______________________ 172 | 173 | old languages (like c or c++) are ASCII code based and number of allowed different ASCII code characters are >= 256 174 | to represent these 256 characters 8 bits are enough hence the size of char in old languages is 1 byte 175 | but java is unicode based number of different unicode characters are > 256 and <= 65536 176 | to represent these many characters 8 ibts may not enough compulsary we should go for 16 bits hence the size of char in java is 177 | 2 bytes. 178 | 179 | Size 2 bytes 180 | range 0 to 65536 181 | 182 | 183 | Summary of java premitive data types : 184 | 185 | data type Size range wrapper class default value 186 | 7 8 187 | 1. byte 1 byte -2 to 2 (-128 to 127) Byte 0 188 | 189 | 15 15 190 | 2. short 2 byte -2 to 2 (-32768 to 32767) Short 0 191 | 192 | 31 31 193 | 3. int 4 byte 2 2 -1 Integer 0 194 | (3147483648 to 3147483647) 195 | 196 | 63 63 197 | 4. long 8 byte 2 2 - 1 Long 0 198 | 199 | 5. float 4 byte -3.4e38 to 3.4e38 Float 0.0 200 | 6. double 8 byte -1.7e308 to 1.7e308 Double 0.0 201 | 7. boolean NA NA(true or false) Boolean false 202 | 8. char 2 byte 0 to 65535 Character 0 [represents space ' ' character] 203 | 204 | 205 | Note : null is default for object reference we can't apply for premitives if we are trying to use for premitive then we will get compile type error. 206 | 207 | e.g char ch = null; CE : incompatable types 208 | found : null 209 | required : char 210 | 211 | -------------------------------------------------------------------------------- /java class_durgasoft/litrals: -------------------------------------------------------------------------------- 1 | Literals 2 | ---------------------- 3 | 4 | 5 | A constant value which can be assigned to the variable is called literal 6 | 7 | e.g int x = 10; 8 | 9 | x is identifier 10 | 11 | 10 is constant value or literal 12 | ____________________ 13 | Integral literals 14 | -------------------- 15 | 16 | For integeral datatypes(byte, short, int, long) we can specify litral value in the following ways. 17 | 18 | 1. Decimal litral(base 10 ) : allowed degits are 0 to 9. 19 | 20 | e.g int x = 10; 21 | 22 | 2. Octal form (base 8) : allowed digits are 0 to 7 23 | 24 | litral value should prefixed with 0. 25 | e.g int x = 010. 26 | 27 | 3. HexaDecimal form (base 16) allowed digits are 0 to 9, a to f 28 | 29 | Note : for extra degits (a to f) we can use both lower case and upper case characters. This is one of very few areas where java is not case sentisitive the litral value should prefixed with '0X' or '0x'. 30 | 31 | int x = 0x10; 32 | int x = 0X10; 33 | 34 | these are only possible ways to specify litral valuefor integral data types 35 | 36 | 37 | which of the following declarations are valid 38 | 39 | int x = 10; valid 40 | int x = 0786; invalid CE: integer number too large. 41 | int x = 0777; valid 42 | int x = 0xFace; valid considered as hexadecimal digits 43 | int x = 0xBeef; valid considered as hexadecimal digits 44 | int x = 0xBeer; invalid CE: ';' required. 45 | 46 | 47 | e.g 2. 48 | programmer having choice to specify valid in octal,decimal or hexadecimal but jvm print these values in decimal form 49 | 50 | e.g 51 | public class Test{ 52 | public static void main(String[] arg){ 53 | 54 | int x = 10; 55 | int y = 010; 56 | int z = 0x10; 57 | 58 | System.out.println(x+ "..." + y + "..." + z); 59 | } 60 | } 61 | 62 | by default every integral literal is of int type but we can specify explicitly as long type by suffixed with 'l' or 'L'. 63 | 64 | e.g 65 | int x = 10; valid 66 | long l = 10l; valid 67 | int x = 10l; invalid CE: possible loss of precision found : long required : int. 68 | long l = 10; 69 | 70 | there is no direct way to specify byte and short litrals explicitly but indirectly we can specify 71 | whenever we are assigning integral litral to the byte variable and if the value within the range of byte then compiler treats it automatically as byte literal similarly short literal also 72 | 73 | byte b = 10 ; valid 74 | byte b = 127; valid 75 | byte b = 128; CE: PLP found int required : byte 76 | 77 | short s = 32767; valid 78 | short s = 32768; CE:PLP found int required short; 79 | 80 | floating point literals 81 | ___________________________ 82 | 83 | 84 | by default every floatting literal is of double type and hence we can't assign directly to float variable. 85 | but we can specify floating point literal as float type by sufixed wiht 'f' or 'F'. 86 | 87 | e.g 88 | float f = 123.456; CE: PLP found:double 89 | required: float 90 | 91 | float f = 123.456F; valid 92 | double d = 123.456; valid 93 | 94 | we can specify explicitly floating point lieral as double type by sufixed with 'd' or 'D'. 95 | offcurse this convension is not required. 96 | 97 | e.g double d = 123.456d; valid 98 | float f = 123.456d;valid CE: PLP found : double required : float 99 | float f = 123.456D;valid CE: PLP found : double required : float 100 | 101 | we can specify floating point literals only in decimal form and we can't specify in octal and hexadecimal forms. 102 | 103 | e.g double d = 123.456; valid 104 | double d = 0123.456; valid treated as double decimal value 105 | double d = 0x123.456; invalid malformed floating point literals. 106 | 107 | we can assign integral literal directly to floating point variables and that integeral literal can be specified either in decimal or octal or hexadecimal forms. 108 | 109 | e.g double d = 0786; invalid; CE : inetger number too large 110 | double d = 0xFACE; valid; 111 | double d = 0786.0; valid 112 | double d = 0xFace.0; invalid; 113 | double d = 010; 114 | double d = 0777; 115 | 116 | 117 | we can't assign floating point literals to integral types. 118 | 119 | e.g 120 | double d = 10; 121 | int x = 10.0; invalid CE: PLP found: double Required : int 122 | 123 | we can specify floating point literal even in exponential form(scientific notation e.g 12.332e2). 124 | 125 | double d = 1.2e3; 126 | sop(d); 127 | 128 | outptu: 129 | -------------- 130 | 1200.0 131 | 132 | float f = 1.2e3; CE : PLP found : double required : float 133 | float f = 1.2e3f; valid 134 | 135 | 136 | Boolean literals : 137 | ___________________ 138 | 139 | the only allowed values for boolean data type are true or false. 140 | 141 | boolean b= true; 142 | 143 | boolean b = 0; incompatable type : found : int required : boolean 144 | 145 | boolean b = True; CE : Cannot find symbol. 146 | symbol : variable True 147 | location : class Test. 148 | 149 | boolean b = "true"; 150 | CE:incompatible type 151 | found : java.lang.String. 152 | required : boolean 153 | 154 | int x = 0; 155 | 156 | if (x) { CE : incompatable type while(1){ 157 | sop("Hello");---> Found : int <--------------------- sopln("Hello"); 158 | } else { Required : boolean } 159 | sop("hi"); 160 | } 161 | 162 | Char Literals 163 | _________________ 164 | 165 | we can specify char literal as single character within single codes 166 | char ch = 'a'; valid 167 | 168 | char ch = a; invalid CE : can not find symbol 169 | Symbol : variable a 170 | location : Test 171 | 172 | char ch = "a"; invalid : CE:incompatable type 173 | found : j.l.String 174 | required : char 175 | 176 | char ch = 'ab'; invalid : CE1 : unclosed char literal (for first '); 177 | CE1 : unclosed char literal (for second '); 178 | CE1 : not a statement; 179 | 180 | we can specify char literal as integral literal which represents unicode value of the character and that integral literal can be specified either in decimal or octal or hexadecimal forms but allowed range is 0 to 65535 181 | 182 | e.g 183 | char ch = 0xFace;valid considered as hexadecimal 184 | char ch = 0777; vlaid considered as octal value 185 | char ch = 65535;valid 186 | char ch = 65536; CE : PLP found : int 187 | required : char 188 | 189 | 3. we can represent char literal in unicode representation which is nothing but '\uxxxx'(4 digit hexadecimal number). 190 | e.g char ch = '\u0061'; 191 | sop(ch); 192 | 193 | output : a 194 | 195 | 4. every escape character is a valid char literal. 196 | 197 | e.g char ch = '\n'; valid 198 | char ch = '\t'; valid 199 | char ch = '\m'; invalid CE: illegal escape character 200 | 201 | 202 | 203 | Escape character Description 204 | 205 | \n New Line 206 | \t horizontal tab 207 | \r carriage return (next line first cell) 208 | \b back space 209 | \f form freed(as like replace) 210 | \' single quote 211 | \" double quote 212 | \\ back slash 213 | 214 | 215 | 216 | which of the following are valid? 217 | 218 | a. char ch = 65536; invalid 219 | b. char ch = 0xBeer; invalid 220 | c. char ch = \uFace; invalid 221 | d. char ch = '\uBeef'; valid 222 | e. char ch = '\m'; invalid 223 | f. char ch = '\iFace'; invalid 224 | 225 | String literals : 226 | ------------------------ 227 | 228 | Any sequence of characters within double codes is treated as string literal. 229 | 230 | e.g 231 | String s = "test abc"; 232 | 233 | 234 | 1.7 version inhancement with respect to lierals 235 | 236 | 1. Binary literals : 237 | 238 | for inegral data types until 1.6 version we can specify lieral value in following ways. 239 | 240 | 1. Decimal form 2. octal form 3. hexa decimal form 241 | 242 | but from 1.7 version onwards we can specify literal value even in binary form also. 243 | allowed degits for binary form are 0 and 1. 244 | 245 | Literal value should be prefixed with '0b' or '0B' 246 | e.g int x = 0b1111; 247 | 248 | Sop(x); 249 | 250 | output : 15 251 | 252 | use of '_' symbol in numeric literals. 253 | ----------------------------------------- 254 | 255 | from 1.7 version onwards we can use '_' symbol between digits of numeric literal 256 | 257 | e.g double d = 123456.789; how we can werite 258 | double d = 123_456.7_8_9; 259 | 260 | the main advantage of this approach is readability of code will be improved. 261 | 262 | at the time of compilation these '_' symbols will be removed automatically hence after compilation the above lines will become 263 | 264 | double d = 123456.789; 265 | 266 | we can use more than one '_' symbol also between digits. 267 | 268 | e.g 269 | double d = 1__23_4_56.7_8_9; valid 270 | 271 | we can use '_' symbol only between digits if we are using anywhere else we will get compile time error. 272 | 273 | double d = _1_23_456.7_8_9; invalid 274 | double d = 1_23_456_.7_8_9; invalid 275 | double d = 1_23_456.7_8_9_; invalid 276 | 277 | 278 | 279 | byte---------->short \ 280 | \ 281 | \ 282 | \ 283 | int----------> long --------------> float ----------> double 284 | / 285 | / 286 | / 287 | / 288 | char 289 | 290 | Note : 8 byte long value we can assign to 4 byte float variable because both are following different memory representations internally. 291 | 292 | e.g 293 | 294 | float f = 10l; 295 | sop(f); 296 | 297 | output : 298 | 10.0; 299 | -------------------------------------------------------------------------------- /java class_durgasoft/main method: -------------------------------------------------------------------------------- 1 | Main Method 2 | ______________ 3 | 4 | whether class contains main method or not and whether main method is declared according to requirement or not these things won't be checked by compiler at runtime JVM is responsible to check these things if JVM unable to find main method then we will get run-time exception saying no such method error:main 5 | 6 | e.g 7 | class Test{ 8 | 9 | } 10 | 11 | javac Test.java 12 | 13 | java Test: 14 | 15 | RE : java.lang.NoSuchMethodError:main 16 | 17 | At runtime JVM always suggest for the main method with the following prototype 18 | 19 | e.g 20 | 21 | public static void main( String[] args) 22 | | | | | | 23 | | | | | | 24 | To call by JVM without any object main Method won't return this is name which Command line 25 | from any where also jvm has to call anything to JVM is confitured in JVM arguments 26 | this method 27 | 28 | The above syntax is very strict and if we perform any change then we will get run time exception saying no such method error:main 29 | 30 | Even though above syntax is very strict the following changes are acceptable. 31 | 32 | 1. instead of public static we can take static public i.e the order of modifiers is not important. 33 | 2. we can declare string[] in any acceptable form. 34 | e.g main(String[] args) 35 | main(String []args) 36 | main(String args[]) 37 | 38 | instead of args we can take any valid java identifier 39 | 40 | main(String[] test) 41 | 42 | we can replace String[] with var-arg parameter 43 | e.g main(String... args) 44 | 45 | we can declare main method with the following modifiers 46 | ____________________________________________________________ 47 | 1. final 2. synchronized 3. strictfp 48 | 49 | e.g public static final synchronized strictfp(String... test) 50 | 51 | Q. Which of the following main method declarations are valid. 52 | 53 | 1. public static void main(String args) //invalid 54 | 2. public static void Main(String[] args) //invalid 55 | 3. public void main(String[] args) //invalid 56 | 4. public static int main(String[] args) //invalid 57 | 5. public synchronized strictfp void main(String[] args) //invalid 58 | 6. public synchronized strictfp static void main(String[] args) //valid 59 | 7. public static void main(String... args) //valid 60 | 61 | 62 | Q 2. in which of the above cases we will get compile time error 63 | 64 | we won't get compile time error any wherer but except last 2 cases in remaining we will Runtime exception saying no such method error:main. 65 | 66 | Case 1: Overloading of the main() method is possible but jvm will always call string[] argument main method only the other overloaded method we have to call explicitly like normal method call. 67 | 68 | e.g 69 | class Test{ 70 | public static void main(String[] args){ 71 | sopln("String array "); 72 | } 73 | public static void msin(int[] args){ 74 | sopln("int array "); 75 | } 76 | 77 | } 78 | 79 | output: 80 | String array. 81 | 82 | Case 2 : inheritance concept applicable for main() method hence while executing child class if child doesn't contain main() then parent class main method() will be executed. 83 | 84 | class P{ 85 | public static void main(String[] arr){ 86 | sopln("parent main"); 87 | } 88 | } 89 | 90 | class c extends p{ 91 | 92 | } 93 | 94 | output 95 | 96 | //java p 97 | 98 | parent main 99 | 100 | //java c 101 | 102 | parent main 103 | 104 | Case 3: 105 | 106 | class P{ 107 | public static void main(String[] args){ 108 | sopln("parent main"); 109 | } 110 | } 111 | 112 | class C extends P{ 113 | public static void main(String[] args){ 114 | sopln("child main"); 115 | } 116 | } 117 | 118 | output for java p: 119 | 120 | parent main 121 | 122 | output for java C: 123 | child main 124 | 125 | it seems overriding concept applicable for main() but it is not overrding and it is method hiding. 126 | 127 | Note : for main method inheritance and overloading concepts are applicable but overriding concept is not applicable. 128 | instead of overriding method hiding is applicable 129 | ______________________________________________________________ 130 | java 1.7 version inhancement with respect to main method 131 | ______________________________________________________________ 132 | 133 | until 1.6 version if the class doesn't contain main method then we will get runtime exception saying NoSuchMethodError:main 134 | 135 | but from 1.7 version onwards instead of no such method error we will get more allobrated error information 136 | 137 | e.g class Test{ 138 | 139 | } 140 | 141 | 1.6 Version 142 | 143 | javac Test.java 144 | java Test 145 | 146 | NoSuchMethodError : main 147 | 148 | 1.7 version 149 | javac Test.java 150 | java Test 151 | 152 | Main method not found in class test please define the main method as : public static void main(String[] args) 153 | 154 | from 1.7 version onwards main method is manidatory to start program execution hence even though class contains static block it won't be executed if the class doesn't contain main() method. 155 | 156 | e.g 157 | 158 | class Test{ 159 | static{ 160 | sop("static block"); 161 | } 162 | } 163 | 164 | output: 165 | 1.6 version 166 | 167 | javac Test.java 168 | java Test 169 | 170 | static block 171 | RE:noSuchMethodFoundError:main 172 | 173 | in 1.7 version 174 | 175 | javac Test.java 176 | java Test 177 | 178 | Error : Main method not found in class Test... 179 | 180 | e.g 2 181 | 182 | class Test{ 183 | static{ 184 | sopln("Static block"); 185 | exit(0); 186 | } 187 | } 188 | 189 | output: 190 | 1.6 version 191 | javac Test.java 192 | java Test 193 | 194 | static block 195 | 196 | 197 | in 1.7 version 198 | 199 | javac Test.java 200 | java Test 201 | 202 | Error : Main method not found in class Test... 203 | 204 | case 3 : 205 | 206 | class Test{ 207 | static{ 208 | sopln("static block"); 209 | } 210 | public static void main(String[] args){ 211 | 212 | } 213 | } 214 | 215 | output: 216 | 1.6 version 217 | javac Test.java 218 | java Test 219 | 220 | static block 221 | 222 | 223 | in 1.7 version 224 | 225 | javac Test.java 226 | java Test 227 | 228 | static block 229 | 230 | 231 | 1.6 version flow 232 | 233 | Identification 234 | of static members 235 | | 236 | | 237 | Execute static block not available 238 | and static variable---------------------- 239 | assignments | 240 | | | 241 | | | 242 | check for main | 243 | method | 244 | | | 245 | | | 246 | | if available | 247 | | | 248 | Execute main RE: noSuchMethodError:main 249 | 250 | 251 | 252 | in 1.7 version 253 | 254 | Identification 255 | of static members 256 | | 257 | | 258 | check for main Not available 259 | method --------------------------------- 260 | | | 261 | | if available | 262 | | | 263 | | | 264 | Identificaion of NoSuchMethodError:main 265 | all static members 266 | | 267 | | 268 | | 269 | Execution of static 270 | variable assignment 271 | and static block 272 | | 273 | | 274 | | 275 | | 276 | Execute main 277 | 278 | 279 | Q. Without writing main method is it possible to print some statements to the console? 280 | 281 | Yes but using static block. 282 | But this rule is applicable until 1.6 version 283 | but 1.7 version onwards it is impossible to print some statement to the console without writing main method. 284 | 285 | 286 | 287 | -------------------------------------------------------------------------------- /java class_durgasoft/oop's concepts - 1: -------------------------------------------------------------------------------- 1 | ______________________ 2 | OOPs Conceptes | 3 | ______________________| 4 | 5 | 1. Data Hiding 6 | 2. Abstraction 7 | 3. Encapsulation 8 | 4. Tightly encapsulate class 9 | 5. Is A relationship 10 | 6. Has a relationship 11 | 7. Method signature 12 | *8. Overloading 13 | *9. Overriding 14 | *10. Static control flow 15 | *11. Instance Control flow 16 | *12. Constructor 17 | 13. Coupling 18 | 14. Cohesion 19 | 15. Type-Casting 20 | 21 | 22 | __________________ 23 | 1. Data Hiding 24 | __________________ 25 | 26 | Outside person can't access our internal data directly or our internal data should not go out directly this oop feature is nothing but data hiding. After validation or authentication outside person can access our internal data 27 | 28 | e.g 1. After providing proper user name and password we can able to access our gmail in-box information. 29 | 2. even though we are valid customer of the bank we can able to access our account information and we can't access others account information 30 | 31 | By declaring data member (variables) as private we can achieve data hiding 32 | 33 | e.g public class account{ 34 | private double balance; 35 | public double getBalance(){ 36 | //if person valid 37 | return balance; 38 | } 39 | } 40 | 41 | the main advantage of data hiding is security 42 | Note : it is highly recommended to declare data member(variable) as private 43 | ________________ 44 | 2.Abstraction 45 | ________________ 46 | 47 | Hiding internal implementation and just highlight the set of services what we are offering is the concept of abstraction. 48 | throw bank ATM gui screen bank people are highlighting the set of services what they are offering without highlighting internal implementation 49 | 50 | the main advantages of abstraction are 51 | 1. we can achieve security because we are not highlighting our internal implementation. 52 | 2. without affecting outside person we can able to perform any type of changes in our internal system and hence enhancement will become easy. 53 | 3. it improves maintainability of the application. 54 | 4. it improves easiness to use our system. 55 | 5. by using interfaces and abstract classes we can implement abstraction. 56 | 57 | __________________ 58 | 3. encapsulation 59 | __________________ 60 | 61 | The process of binding data and corresponding methods into a single unit is nothing but encapsulation 62 | 63 | e.g class Student{ 64 | //data members (instance variables) + methods (behavior) 65 | } 66 | 67 | as like codact capsul 68 | 69 | if any component follows data hiding and abstraction such type of component is said to be encapsulated component 70 | 71 | encapsulation = datahiding + abstraction; 72 | 73 | public class Account{ 74 | private double balance; 75 | 76 | public double getBalance(){ _______________________ 77 | // validation | | 78 | | | 79 | return balance;----------------------------------------->| Balance inquiry | 80 | } | | 81 | public void setBalance(double balance){ | | 82 | this.balance = balance;--------------------------------->| Update balance | 83 | } | | 84 | } | | 85 | |______________________| 86 | perform GUI operations 87 | 88 | 89 | The main advantages of encapsulation are 90 | 1. security 91 | 2. enhancement become easy : it improves maintainability of the application 92 | 93 | The main advantage of encapsulation is we can achieve security but the main disadvantage of encapsulation is it increase length of the code and slows down execution. 94 | 95 | ___________________________ 96 | Tightly encapsulated class 97 | ___________________________ 98 | A class is said to be tightly encapsulated if and only if each and every variable declared as private. 99 | whether class contains corresponding getter and setter methods are not and whether these methods are declared as public or not these things we are not required to check. 100 | 101 | e.g public class Account{ 102 | private double balance; 103 | 104 | public double getBalance(){ 105 | return balance; 106 | } 107 | } 108 | 109 | 110 | Q. which of the following classes are tightly encapsulated. 111 | 112 | ans: a. 113 | class A{------------------------------------> valid 114 | private int x = 10; 115 | } 116 | 117 | class B extends A{--------------------------> invalid 118 | int y = 20; 119 | } 120 | 121 | class c extends B{--------------------------> valid 122 | private int z = 30; 123 | } 124 | 125 | b. 126 | class A{------------------------------------> invalid 127 | int x = 10; 128 | } 129 | 130 | class B extends A{--------------------------> invalid 131 | int y = 20; 132 | } 133 | 134 | class c extends B{--------------------------> invalid 135 | private int z = 30; 136 | } 137 | 138 | 139 | Note: if the parent class is not tightly encapsulated then no child class is tightly encapsulated 140 | 141 | 142 | ______________________ 143 | Is-A relationship 144 | ______________________ 145 | 146 | 1. It is also known as inheritance. 147 | 2. The main advantage of is-a relationship is code re-usability. 148 | 3. By using extends keyword we can implement is-a relationship. 149 | 150 | class P{ 151 | public void m1(){ 152 | sopln("parent"); 153 | } 154 | } 155 | class C extends P{ 156 | public void m2(){ 157 | sopln("child"); 158 | } 159 | } 160 | 161 | 1. P p1 = new P(); 162 | 163 | p1.m1();// valid 164 | p1.m2();// invalid CE: cannot find symbol p1.m2() symbol: method m1() location : Variable p2() of type Parent 165 | 166 | 2. C c1 = new C(); 167 | 168 | p1.m1();// valid 169 | p1.m2();// valid 170 | 171 | 3. P p1 = new C(); 172 | 173 | p1.m1();// valid 174 | p1.m2();// invalid : CE: cannot find symbol p2.m2() symbol : method m1() location : Variable p2() of type Parent 175 | 176 | 4. C p1 = new P(); 177 | CE: incompatible types found : P required : C 178 | 179 | 1. whatever methods parent has by default available to the child and hence on the child reference we can call both parent and child methods. 180 | 2. whatever methods child has by default not available to the parent and hence on the parent reference we can't call child specific methods. 181 | 3. parent reference can be used to hold child object but using that reference we can't call child specific methods but we can call the methods present in parent class. 182 | 4. Parent reference can be used to hold child object but child reference can't used to hold parent object. 183 | 184 | Without inheritance: 185 | 186 | class vahicleLoan{ 187 | //300 methods 188 | } 189 | 190 | class HomeLoan{ 191 | //300 methods 192 | } 193 | 194 | class PersonalLoan{ 195 | //300 methods 196 | } 197 | 198 | With niheritance : 199 | 200 | class Loan{ 201 | //250 methods 202 | } 203 | 204 | class VehicleLoan extends Loan{ 205 | //write remaining 50 methods 206 | } 207 | 208 | class HousingLoan extends Loan{ 209 | //write remaining 50 methods 210 | } 211 | 212 | class PersonalLoan extends Loan{ 213 | //write remaining 50 methods 214 | } 215 | 216 | Note : the most common methods which applicable for any type of child, we have to define in parent class. 217 | the specific methods which are applicable for a particular child we have to define in child class. 218 | 219 | Total java API is implemented based on inheritance concept 220 | 221 | The most common methods which are applicable for any java object are defined in object class. 222 | 223 | and hence every class in java is the child class of object either directly or indirectly so that object class methods by default available to every java class without rewriting due to this Object class access root for all java classes. 224 | 225 | Throwable class defines the most common methods which are required for every exception and error classes hence this class acts as root for java exception hierarchy. 226 | 227 | 228 | 229 | 230 | Object 231 | /| \ 232 | / | \ 233 | / | \ 234 | / | \ 235 | / | \ 236 | / | \ 237 | / | \ 238 | / | \ 239 | / | \ 240 | / | \ 241 | / | \ 242 | / | \ 243 | String StringBuffer Throwable 244 | /\ 245 | / \ 246 | / \ 247 | / \ 248 | / \ 249 | / \ 250 | Exception Error 251 | /\ 252 | / \ 253 | / \ 254 | RE Exception 255 | 256 | ______________________ 257 | Multiple Inheritance | 258 | ______________________| 259 | 260 | A java class can't extends more than one class at a time hence java won't provide support for multiple inheritance in classes 261 | 262 | e.g 263 | class A extends B,C{ 264 | 265 | } 266 | 267 | output : invalid CE: 268 | 269 | Note : 1. if our class doesn't extend any other class then only our class is direct child class of object 270 | class A{ 271 | 272 | } 273 | child of 274 | A--------------->object 275 | 276 | if our class extends other class then our class is indirect child class of object. 277 | e.g 278 | class A{ 279 | 280 | } 281 | 282 | class B extends A{ 283 | 284 | } 285 | child of 286 | B----------------->A 287 | child of 288 | B----------------->Object //invalid 289 | 290 | child of child of 291 | B----------------->A----------------->Object//valid 292 | 293 | Note : either directly or indirectly java won't provide support for multiple inheritance with respect to classes. 294 | 295 | Q. Why java won't provide support for multiple inheritance. 296 | ____________________________________________________________ 297 | 298 | there may be a chance of ambiguity problem hence java won't provide support for multiple inheritance. 299 | 300 | 301 | p1.m1() p2.m1() 302 | \ / 303 | \ / 304 | \ / 305 | \ / 306 | \ / 307 | \ / 308 | \/ 309 | C 310 | ambiguity problem 311 | 312 | But interface can extends any number of interfaces simultaneously hence java provides support for multiple inheritance with respect to interfaces. 313 | 314 | e.g 315 | 316 | interface A{ 317 | } 318 | 319 | interface B{ 320 | } 321 | 322 | interface C extends A, B{ 323 | } 324 | 325 | Q. why ambiguity problem won't be there in interfaces? 326 | _________________________________________________________ 327 | Ans : 328 | 329 | PI1.m1() PI2.m1() 330 | \ / 331 | \ / 332 | \ / 333 | \ / 334 | \ / 335 | \ / 336 | \/ 337 | CI----->m1() 338 | | 339 | | 340 | | 341 | | 342 | | 343 | | 344 | Implementation ---------> m1(){} 345 | Class 346 | 347 | Even though multiple method declarations are available but implementation is unique and hence there is no chance of ambiguity problem in interfaces. 348 | 349 | Note : strictly speaking throw interfaces we won't get any inheritance. 350 | _____________________ 351 | Cyclic Inheritance | 352 | _____________________| 353 | cyclic inheritance is not allowed in java off-course it's not required 354 | e.g 355 | class A extends A{}//CE: Cyclic inheritance is not allowed in java, it's not required 356 | 357 | class A extends B{}//CE: Cyclic inheritance is not allowed in java, it's not required 358 | 359 | class B extends A{}//CE: Cyclic inheritance is not allowed in java, it's not required 360 | 361 | 362 | 363 | 364 | -------------------------------------------------------------------------------- /java class_durgasoft/questions: -------------------------------------------------------------------------------- 1 | https://www.hackerearth.com/star-wars-the-code-wars/?utm_campaign=user-activity-email&utm_medium=email&utm_source=user-challenge-reminder 2 | 3 | What's Separatist Planning ???? 4 | Max. Marks: 40 5 | 6 | Before the Battle of Kamino the Confederacy of Independent Systems developed the a way to communicate with the far systems. This way is very unique as every word consists of exactly L lowercase letters. Also, there are exactly D words in this. 7 | 8 | Jedi order intercept these messages and built a dictionary out of it. Now they have to dechiper it to get the messages the Confederacy of Independent Systems transmitting. Unfortunately, these signals are not intercepted properly and some of the words may be misinterpreted. In order to help them decipher these messages, the Jedi order have asked you to devise an algorithm that will determine the number of possible interpretations for a given pattern. 9 | 10 | A pattern consists of exactly L tokens. Each token is either a single lowercase letter (the Jedi are very sure that this is the letter) or a group of unique lowercase letters surrounded by parenthesis ( and ). For example: (ab)d(dc) means the first letter is either a or b, the second letter is definitely d and the last letter is either d or c. Therefore, the pattern (ab)d(dc) can stand for either one of these 4 possibilities: add, adc, bdd, bdc. 11 | 12 | Input 13 | 14 | The first line of input contains 3 integers, L, D and N separated by a space. D lines follow, each containing one word of length L. These are the words that are known to exist in the message. N test cases then follow, each on its own line and each consisting of a pattern as described above. You may assume that all known words provided are unique. 15 | 16 | Output 17 | 18 | For each test case, output should be K indicating how many words in the message match the pattern. 19 | 20 | Limits 21 | 22 | 1 ≤ L ≤ 15 1 ≤ D ≤ 5000 1 ≤ N ≤ 500 23 | 24 | 25 | 26 | SAMPLE INPUT 27 | 28 | 3 5 4 29 | abc 30 | bca 31 | dac 32 | dbc 33 | cba 34 | (ab)(bc)(ca) 35 | abc 36 | (abc)(abc)(abc) 37 | (zyx)bc 38 | 39 | SAMPLE OUTPUT 40 | 41 | 2 42 | 1 43 | 3 44 | 0 45 | 46 | 47 | 48 | Separatist 49 | 50 | Always finding new ways to destroy the Republic forces by surprise attacks. 51 | 52 | Now they trapped the Republic fleet near the Abregado system. They have developed a way to communicate through the encrypted message to its fleet around the Abregado system. 53 | 54 | They wrote a message in a cryptic language, and next to it they wrote a series of symbols. Republic fleet intercept these messages and concluded that the symbols indicate a number: the number of seconds before they launch next surprise attack on them! 55 | 56 | Unfortunately Republic Fleet have no idea what each symbol means. They have decided that each symbol indicates one digit, but they aren't sure what each digit means or what base the Separatists are using. For example, if Separatist wrote "ab2ac999", they could have meant "31536000" in base 10 -- exactly one year -- or they could have meant "12314555" in base 6 -- 398951 seconds, or about four and a half days. Republic fleet are sure of three things: the number is positive; like us, the Separatists will never start a number with a zero; and they aren't using unary (base 1). 57 | 58 | Your job is to determine the minimum possible number of seconds they launch next surprise attack on them. 59 | 60 | Input 61 | 62 | The first line of input contains a single integer, T. T test cases follow. Each test case is a string on a line by itself. The line will contain only characters in the 'a' to 'z' and '0' to '9' ranges (with no spaces and no punctuation), representing the message by Separatists. The test cases are independent, and can be in different bases with the symbols meaning different things. 63 | 64 | Output 65 | 66 | For each test case, output V the minimum number of seconds before the next surprise attack. 67 | 68 | Limits 69 | 70 | 1 ≤ T ≤ 100 The answer will never exceed 10^18 71 | 72 | 1 ≤ the length of each line < 61 73 | SAMPLE INPUT 74 | 75 | 3 76 | 11001001 77 | cats 78 | zig 79 | 80 | SAMPLE OUTPUT 81 | 82 | 201 83 | 75 84 | 11 85 | 86 | 87 | -------------------------------------------------------------------------------- /java class_durgasoft/tests/ans: -------------------------------------------------------------------------------- 1 | Q4. a,(b),c 2 | 3 | q5. a 4 | 5 | q6. a,e 6 | 7 | q7. c 8 | 9 | q8. 10 | 11 | q9. (wrong c,f)(d,e) 12 | 13 | q10. d or e 14 | 15 | q11. b 16 | 17 | q12. (wront b) a 18 | 19 | q13. b,d 20 | 21 | q14. b 22 | 23 | q15. 24 | 25 | q16. 26 | 27 | q17. 28 | 29 | q18. 30 | 31 | q19. 32 | 33 | q20. 34 | 35 | q21. 36 | 37 | q22. 38 | 39 | q23. 40 | 41 | q24. 42 | 43 | q25. 44 | 45 | q26. 46 | 47 | q27. 48 | 49 | q28. 50 | 51 | q29. 52 | 53 | q30. 54 | 55 | q31. 56 | 57 | q32. 58 | 59 | q33. 60 | 61 | q34. 62 | 63 | q35. 64 | 65 | q36. 66 | 67 | q37. 68 | 69 | q38. 70 | 71 | q39. 72 | 73 | q40. 74 | -------------------------------------------------------------------------------- /java class_durgasoft/tests/ans1: -------------------------------------------------------------------------------- 1 | Q1. b 2 | 3 | Q2. d(run it) 4 | 5 | Q3. a,b,d,e 6 | 7 | Q4. b 8 | 9 | q5. d 10 | 11 | q6. d 12 | 13 | q7. a,b,d 14 | 15 | q8. (wrong e, f) a, e 16 | 17 | q9. (wrong a) b 18 | 19 | q10. c, d 20 | 21 | q11. a 22 | 23 | q12. (Wrong A,C) b, c 24 | 25 | q13. A 26 | 27 | q14. c,d 28 | 29 | q15. (d is wrong) b 30 | 31 | q16. (wrong a) d 32 | 33 | q17. c 34 | 35 | q18. (wrong a) b, c, e 36 | 37 | q19. b 38 | 39 | q20. (wrong b, c, d) b, d, e 40 | 41 | q21. (wrong a, c, d, e) a,b,c,d 42 | 43 | q22. 44 | 45 | q23. 46 | 47 | q24. 48 | 49 | q25. 50 | 51 | q26. 52 | 53 | q27. 54 | 55 | q28. 56 | 57 | q29. 58 | 59 | q30. 60 | 61 | q31. 62 | 63 | q32. 64 | 65 | q33. 66 | 67 | q34. 68 | 69 | q35. 70 | 71 | q36. 72 | 73 | q37. 74 | 75 | q38. 76 | 77 | q39. 78 | 79 | q40. 80 | -------------------------------------------------------------------------------- /java class_durgasoft/var-args: -------------------------------------------------------------------------------- 1 | _______________________________________________________ 2 | Var-Args methods (variable number of artument methods) 3 | _______________________________________________________ 4 | 5 | Until 1.4 version we can't declare a method with variable number of arguments if therer is a change in number of arguments compulsary we should go for new method it increges length of the code and reduces redability. 6 | 7 | to overcome this problem sun people introduced var-arg methods in 1.5 version according to this we can declare a method which can take variable number of arguments such type of methods are called var-arg methods. 8 | 9 | we can declare a var-arg method as follows 10 | 11 | m1(int... x) 12 | 13 | we can call this method by passing any number of int values including 0 number. 14 | 15 | e.g 16 | 17 | class Test{ 18 | public static void main(String[] args){ 19 | m1(); 20 | m1(10); 21 | m1(10,20,30); 22 | m1(10,20,30,40,50,); 23 | } 24 | public static void m1(int... x){ 25 | sopln("Var-arg method"); 26 | } 27 | } 28 | 29 | output : 30 | 31 | Var-arg method 32 | Var-arg method 33 | Var-arg method 34 | Var-arg method 35 | 36 | 37 | internally var-arg parameter will be converted into one dimentional array hence within the var-arg method we can differentiate values by using index 38 | 39 | class Test{ 40 | public static void main(String[] args){ 41 | m1(); 42 | m1(10); 43 | m1(10,20,30); 44 | m1(10,20,30,40,50,); 45 | } 46 | public static void m1(int... x){ 47 | int total = 0; 48 | for(int i : x){ 49 | total = total + i 50 | }sopln("Total : " + total); 51 | } 52 | } 53 | 54 | output: 55 | Total : 0 56 | Total : 10 57 | Total : 60 58 | Total : 150 59 | 60 | case 1: which of the following are valid var-arg method declaration. 61 | 62 | sum(int... x) // valid 63 | sum(int ...x) // valid 64 | sum(int x...) // invalid 65 | sum(int. ..x) // invalid 66 | sum(int .x..) // invalid 67 | sum(int x) // invalid 68 | 69 | case 2 : we can mix var-arg parameter with normal parameter 70 | 71 | e.g m1(int x, int... y);// valid 72 | m1(String x, double... y);// valid 73 | 74 | case 3 : if we mix normal parameter with var-arg parameter then var-arg parameter should be last parameter 75 | 76 | e.g m1(int... y, String s);// invalid 77 | m1(String s, int... y);// valid 78 | 79 | case 4 : inside var-arg method we can take only one var-arg parameter. And we can't take more than one var-arg parameter. 80 | 81 | e.g m1(int... x, double... y) // invalid 82 | 83 | case 5: inside a class we can't declare var-arg method and corresponding one dimentional array method symulteniously otherwise we will get compile-time error. 84 | 85 | class Test{ 86 | public static void m1(int... x){ 87 | 88 | } 89 | 90 | public static void m1(int[] x){ 91 | 92 | } 93 | } 94 | 95 | output: CE: can't declare m1(int[]) and m1(int...) in Test. 96 | 97 | case 6 : 98 | 99 | class Test{ 100 | public static void m1(int... x){ 101 | sopln("var-arg method"); 102 | } 103 | 104 | public static void m1(int x){ 105 | sopln("general method"); 106 | } 107 | 108 | public static void main(String[] args){ 109 | m1(); 110 | m1(10,20); 111 | m1(10); 112 | } 113 | } 114 | 115 | output: 116 | var-arg method 117 | var-arg method 118 | general method 119 | 120 | in general var-arg method will get least priority. i.e if no other method matched then only var-arg method will get chance. 121 | it is exactly same as default case inside switch. 122 | 123 | Equivalence between var-arg parameter and one dimentional array. 124 | wherever one dimentional array present we can replace with var-arg parameter 125 | 126 | m1(int[] x) => m1(int... x) 127 | 128 | e.g main(String[] args) => main(String... args) 129 | 130 | wherever var-arg parameter present we can't replace with one-dimentional array 131 | 132 | m1(int... x) => m1(int[] x) 133 | _____________ 134 | imp Note: 135 | _____________ 136 | 137 | m1(int... x) 138 | 139 | we can call this method by passing a group of int values and x- will become one dimentional array. 140 | 141 | m1(int[]... x) 142 | 143 | we can call this method by passing a group of one dimentional int arrays and x will become two dimentional int array. 144 | 145 | e.g class Test{ 146 | public static void main(String[] args){ 147 | int[] a = new int[]{10,20,30}; 148 | int[] b = new int[]{40,50,60}; 149 | 150 | 151 | } 152 | public static void m1(int[]... arr){ 153 | for(int x[] : arr){ 154 | sopln(x[0]); 155 | } 156 | 157 | } 158 | } 159 | 160 | -------------------------------------------------------------------------------- /java_io: -------------------------------------------------------------------------------- 1 | File I/O 2 | 3 | 1.File 4 | 2. FileWriter 5 | 3. FileReader 6 | 4. BufferedWriter 7 | 5. BufferedReader 8 | 4. PrintWriter 9 | 10 | File 11 | ___________ 12 | 13 | File f = new File("abc.txt"); 14 | this line won't create any physical file 1st it will check is there any physical file named with "abc.txt" is available or not if it is available then 'f' simply refers that file. If it is not available then we are just creating java file object to represent the name abc.txt. 15 | 16 | 17 | File f = new File("abc.txt"); 18 | 19 | sopln(f.exists()); false 20 | 21 | f.createNewFile(); 22 | 23 | sopln(f.exists()); true 24 | 25 | 1st run-----> false true 26 | 27 | 2nd run-----> true true 28 | 29 | we can use java file object to represent directory also. 30 | 31 | File f = new File("durga123"); 32 | 33 | sopln(f.exist());//false 34 | 35 | f.mkdir(); 36 | 37 | sopln(f.exist());//true 38 | 39 | 40 | Note: in unix every thing is treated as a file java file I/O concept is implemented based on Unix operating system. Hence java file Object can be used to represent both files and directories. 41 | 42 | File class Constructors 43 | __________________________ 44 | 45 | 1. File f = new File(String name); 46 | 47 | it creates a java file object to represent name of the file or directory in current working directory. 48 | 49 | 2. File f = new File(string subDirName, String name); 50 | 51 | it creates a java file object to represent name of the file or directory present in specified sub directory 52 | 53 | 3. File f = new File(File subDir, String name) 54 | 55 | same as above. 56 | 57 | e.g. 1. Write code to create a file name with abc.txt in current working directory. 58 | 59 | File f = new File("abc.txt"); 60 | f.createNewFile(); 61 | 62 | 2. Write code to create a directory named with "Durga123" in current working directory, and create a File name with "demo.txt" in that directory 63 | 64 | File f = new File("abc.txt"); 65 | f1.mkdir(); 66 | File f1 = new File("Durga123","demo.txt"); 67 | 68 | File f1 = new File(f, "demo.txt"); 69 | 70 | f1.createNewFile(); 71 | 72 | e.g 3.Write code to create a file named abc.txt in E:\xyz folder. 73 | 74 | File f = new File ("E://xyz", "abc.txt"); 75 | 76 | f.createNewFile(); 77 | 78 | Assume that E://xyz folder already available in out system. 79 | 80 | Important methods present in file class: 81 | _____________________________________________ 82 | 83 | 1. boolean exist(); Returns true if the specified file or directory available. 84 | 2. boolean createNewFile() : First this method will check whether the specified file is already available or not. If it is already available then this method returns false without creating any physical file. 85 | If the file is not already available then this method will creates new file and returns true. 86 | 3. boolean mkdir() : same as above. 87 | 88 | 4. boolean isFile() : Returns true if the specified file object pointing to physical file. 89 | 90 | 5. boolean isDirectory() : Returns true if f pointing to directory. 91 | 92 | 6. String[] list() : this method returns the names of all files and sub directories present in specified directory. 93 | 94 | 7. long length() : returns number of characters present in specified file. 95 | 96 | 8. boolean delete() : to delete specified file or directory 97 | 98 | Write a program to display the names of all files and directories present in C:/test 99 | 100 | import java.io.*; 101 | 102 | class Test{ 103 | public static void main(String[] args){ 104 | int count = 0; 105 | 106 | File f = new File("C:\\durga_classes"); 107 | String[] s = f.list(); 108 | for(String s1 : s){ 109 | count++; 110 | System.out.println(s1); 111 | } 112 | System.out.println("The total number : " + count); 113 | } 114 | } 115 | 116 | To display only file names : 117 | __________________________________ 118 | int count = 0; 119 | File f = new File("C://durgasoft"); 120 | String[] s1 = f.list(); 121 | 122 | for(String s1 : s){ 123 | File f = new File(s1); 124 | if (f.isFile()){ 125 | count++; 126 | sopln(f, s1); 127 | } 128 | } 129 | 130 | To display only Directory names: 131 | __________________________________ 132 | 133 | int count = 0; 134 | File f = new File("C://durgasoft"); 135 | String[] s1 = f.list(); 136 | 137 | for(String s1 : s){ 138 | File f = new File(s1); 139 | if (f.isDirectory()){ 140 | count++; 141 | sopln(f, s1); 142 | } 143 | } 144 | 145 | The above fileWriters ment for overriding of existing data. Instead of overriding if we want append operation then we have to create FileWriter by using the following constructors. 146 | 147 | 3. FileWriter fw = new FileWriter(String fileName, boolean append); 148 | 149 | 4. FileWriter fw = new FileWriter(File f, boolean append); 150 | 151 | Note : if the specified file is not already available then all the above constructors will create that file. 152 | 153 | 1. Write(int ch) to write a single character 154 | 155 | 2. Write(char[] ch) to write a array of characters. 156 | 157 | 3. write(String s) to write an string to the file 158 | 159 | 4. flush() to give guaranty that total data including last character will be return to the file. 160 | 161 | 5. close() to close the writer. 162 | 163 | FileWriter 164 | _______________ 165 | we can use fileWriter to write character data to the file 166 | 167 | Constructors: 168 | _____________ 169 | FileWriter fw = new FileWriter(String fileName); 170 | 171 | FileWriter fw = new FileWriter(File f); 172 | 173 | import java.io.*; 174 | 175 | class FileWriterDemo2{ 176 | public static void main(String[] args) throws IOException{ 177 | FileWriter fw = new FileWriter("abc.txt"); 178 | fw.write(100); 179 | fw.write("urg\nsoftwaresolutions"); 180 | fw.write('\n'); 181 | char[] ch1 = {'a','b','c'}; 182 | fw.write(ch1); 183 | fw.write('\n'); 184 | fw.flush(); 185 | fw.close(); 186 | } 187 | } 188 | 189 | output : 190 | durga 191 | softwaresolution 192 | abc 193 | 194 | In the above program fileWriter can perform overriding of existing data instead of overriding if we want append operation then we have to create fileWriter object as follows. 195 | 196 | FileWriter fw = new FileWriter("abc.txt", true); 197 | 198 | Note : The main problem with FileWriter is we have to insert line separator (\n) manually which is varied from System to System. It is difficulty to the programmer. We can solve this problem by using BufferedWriter and PrintWriter classes. 199 | 200 | FileReader 201 | _______________ 202 | We can use FileReader to read character data from file 203 | 204 | Constructors : 205 | 206 | 1. FileReader fr = new FileReader(String fileName); 207 | 2. FileReader fr = new FileReader(File f); 208 | 209 | Methods : 210 | 211 | 1. int read():it attempts to read next character from the file and returns its uni-code valueif next character not available then this method returns -1. As this method returns unicode value (int value), at the time of printing we have to perform typecasting. 212 | 213 | FileWriter fr = new FileWriter("abc.txt"); 214 | int i = fr.read(); 215 | while(i != -1){ 216 | soprint((Char)i); 217 | i = fr.read(); 218 | } 219 | 220 | 2. int read(char[] ch); 221 | 222 | It attempts to read enough characters from the file into char array. And returns number of characters copied from the file. 223 | 224 | File f = new File("abc.txt"); 225 | char[] ch = new Char[(int) f.length]; 226 | FR fr = new FR(f); 227 | fr.read(ch); 228 | 229 | for(Char ch1 : ch){ 230 | sopln(ch1); 231 | } 232 | 233 | 3. void close(); 234 | 235 | import java.io.*; 236 | 237 | class FileReaderDemo{ 238 | public static void main(String[] args){ 239 | File f = new File("abc.txt"); 240 | FileReader fr = new FileReader(f); 241 | char[] ch = new char[(int) f.length()]; 242 | fr.read(ch); 243 | for(char ch1 : ch){ 244 | System.out.print(ch1); 245 | } 246 | System.out.println("**************************"); 247 | FileReader fr1 = new FileReader("abc.txt"); 248 | int i = fr1.read(); 249 | while(i!= -1){ 250 | System.out.println((char)i); 251 | i = fr1.read(); 252 | } 253 | } 254 | } 255 | 256 | Note : By using FileReader we can read data character by character which is not convenient to the programmer. 257 | 258 | Usage of FileWriter and FileReader is not recommended because 259 | 260 | 1. while writing data by fileWriter we have to insert line seprator(\n) manually which is varied from System to system it is difficult to the programmer. 261 | 262 | 2. By using FileReader we can read data character by character, which is not convenient to the programmer. 263 | 264 | 3. To overcome these problems we should go for BufferedReader and BufferedReader. 265 | 266 | 4. BufferedWriter : we can use BufferedWriter to write character data to the file. 267 | 268 | Constructors : 269 | ________________ 270 | 271 | 1. BufferedWriter bw = new BufferedWriter(Writer w); 272 | 2. BufferedWriter bw = new BufferedWriter(Writer w, int BufferSize); 273 | 274 | Note : BufferedWriter can't communicate directly with the file. it can communicate via some Writer object. 275 | 276 | Q. Which of the following are valid 277 | 278 | 1. BufferedWriter bw = new BufferedWriter("abc.txt");//invalid 279 | 2. BufferedWriter bw = new BufferedWriter(new File("abc.txt"));//invalid 280 | 3. BufferedWriter bw = new BufferedWriter(new FileWriter("abc.txt"));//valid 281 | 4. BufferedWriter bw = new BufferedWriter(new BufferedWriter(new FileWriter("abc.txt"))); //valid 282 | 283 | 284 | Methods 285 | __________ 286 | 287 | 1. write(int ch) 288 | 2. write(char[] ch) 289 | 3. write(String s) 290 | 4. flush() 291 | 5. close() 292 | 6. newLine(); To insert a line separator. 293 | 294 | Q. When compared with the FileWriter which of the following capability available extra in method form in BufferedWriter. 295 | 296 | 1. Writing data to the file 297 | 2. close the file 298 | 3. flushing the file 299 | 4. inserting a new line character. 300 | 301 | import java.io.*; 302 | class BufferedWriterDemo{ 303 | public static void main(String[] args) throws IOException{ 304 | FileWriter fw = new FileWriter("abc.txt"); 305 | BufferedWriter bw = new BufferedWriter(fw); 306 | bw.writer(100); 307 | bw.newLine(); 308 | char[] ch1 = {'a','b','c','d'}; 309 | bw.write(ch1); 310 | bw.newLine(); 311 | bw.write("durga"); 312 | bw.newLine(); 313 | bw.write("Software solutions"); 314 | bw.flush(); 315 | bw.close(); 316 | } 317 | } 318 | 319 | output: 320 | 321 | d 322 | abcd 323 | durga 324 | SoftwareSolutions 325 | 326 | 327 | Note : Whenever we are closing BufferedWriter automatically internal FileWriter will be closed and we are not required to close explicitly. 328 | 329 | bw.close(); fw.close(); bw.close(); 330 | fw.close(); 331 | 332 | valid invalid invalid 333 | 334 | _____________________ 335 | BufferedReader 336 | _____________________ 337 | we can use BufferedReader to read character data from the file. 338 | The main advantage of BufferedReader when compared with FileReader is we can read data line by line in addition to character by character. 339 | 340 | Constructors 341 | _______________ 342 | 343 | 1. BufferedReader br = new BufferedReader(Reader r); 344 | 2. BufferedReader br = new BufferedReader(Reader r, int bufferSize); 345 | 346 | Note : BufferedReader can't communicate directly with the file and it can communicate via some Reader object. 347 | 348 | Methods 349 | _________ 350 | 1. int read(); 351 | 2. int read(char[] ch) 352 | 3. void close(); 353 | 4. String readLine(); It attempts to read next line from the file and returns it. If the next line not available then this method returns null. 354 | 355 | import java.io.*; 356 | 357 | class BufferedReaderDemo{ 358 | public static void main(String[] args) throws IOException{ 359 | FileReader fr = new FileReader("abc.txt"); 360 | String line = br.readLine(); 361 | while(line != null){ 362 | System.out.println(ln); 363 | line = br.readLine(); 364 | } 365 | br.close(); 366 | } 367 | } 368 | 369 | Note : Whenever we are closing BufferedReader automatically underlying FileReader will be closed and we are not required to close explicitly. 370 | 371 | Note : The most enhanced reader to read character data from the file is BufferedReader. 372 | 373 | _____________ 374 | PrintWriter 375 | _____________ 376 | 377 | It is the most enhanced writer to write character data to the file. The main advantage of PrintWriter over FileWriter and BufferedWriter is we can write any type of primitive directly to the file 378 | _____________________ 379 | Constructors : 380 | _____________________ 381 | 382 | 1. PrintWriter pw = new PrintWriter(String fileName); 383 | 2. PrintWriter pw = new PrintWriter(File f); 384 | 3. PrintWriter pw = new PrintWriter(Writer w); 385 | 386 | Note : PrintWriter can communicate with directly with the file and can communicate via some writer object also. 387 | 388 | Methods : 389 | __________ 390 | 391 | 1. write(int ch) 392 | 2. write(String s) 393 | 3. write(Char[] ch) 394 | 4. flush(); 395 | 5. close(); 396 | 397 | print(char ch); 398 | print(int i); 399 | print(double d); 400 | print(String s); 401 | ............ 402 | 403 | println(char ch); 404 | println(int i); 405 | println(double d); 406 | println(String s); 407 | ............ 408 | 409 | class PrintWriterDemo1{ 410 | public static void main(String[] args) throws IOException{ 411 | FileWriter fw = new FileWriter("abc.txt"); 412 | PrintWriter out = new PrintWriter(fw); 413 | out.write(100); 414 | out.println(100); 415 | out.println(true); 416 | out.println('c'); 417 | out.println("durga"); 418 | out.flush(); 419 | out.close(); 420 | } 421 | } 422 | 423 | output: 424 | 425 | d100 426 | true 427 | c 428 | durga 429 | 430 | Q. What is the difference between write(100) and print(100). 431 | 432 | Ans. In the case of write(100) the corresponding character d will be added to the file but in the case of print(100) the int value 100 will be added to the file directly. 433 | 434 | Note : the most enhanced writer to write character data to the file is PrintWriter where as the most enhanced reader to read character data from the file is BufferedReader. 435 | 436 | 437 | 438 | Note : In general we can use Readers and Writers to handle character data(text data), where as we can use streams to handle binary data(like images, PDF files, Video files, Audio files etc.) 439 | 440 | we can use outputStream to write Binary data to the file, inputStream to read Binary data from the file. 441 | 442 | Object 443 | /\ 444 | / \ 445 | / \ 446 | / \ 447 | / \ 448 | / \ 449 | / \ 450 | / \ 451 | / \ 452 | / \ 453 | Writer(ac) Reader(AC) 454 | /|\ / \ 455 | / | \ / \ 456 | / | \ / \ 457 | / | \ / \ 458 | / | \ / \ 459 | / | \ / \ 460 | / | \ / \ 461 | / | \ / \ 462 | / | \ / \ 463 | Output Buffered Print Input BufferedReader 464 | Stream Writer Writer Stream 465 | Writer Reader 466 | | | 467 | | | 468 | | | 469 | | | 470 | FileWriter FileReader 471 | 472 | 473 | Q. Write a program to Merge a data from two files in a third file. 474 | 475 | 476 | import java.io.*; 477 | 478 | class FileMerger{ 479 | public static void main(String[] args)throws IOException{ 480 | PrintWriter pw = new PrintWriter("File3.txt"); 481 | BufferedReader br = new BufferedReader(new FileReader("file1.txt")); 482 | String line = br.readLine(); 483 | while(line != null){ 484 | pw.println(line); 485 | line = br.readLine(); 486 | } 487 | br = new BufferedReader(new FileReader("File2.txt")); 488 | line = br.readLine(); 489 | while(line != null){ 490 | pw.println(line); 491 | line = br.readLine(); 492 | } 493 | pw.flush(); 494 | br.read(); 495 | pw.close(); 496 | } 497 | } 498 | 499 | aaa 222 500 | bbb 333 501 | ccc 444 502 | 555 503 | 504 | aaa 505 | bbb 506 | ccc 507 | 222 508 | 333 509 | 444 510 | 555 511 | 512 | Write a program to perform file merge operation where merging should be done line by line alternatively. 513 | 514 | import java.io.*; 515 | 516 | class FileMerger2{ 517 | public static void main(String[]args)throws IOException{ 518 | PrintWriter pw = new PrintWriter("File.txt"); 519 | BufferedReader br1 = new BufferedReader(new FileReader("file1.txt")); 520 | BufferedReader br2 = new BufferedReader(new FileReader("file2.txt")); 521 | String line1 = br1.readLine(); 522 | String line2 = br2.readLine(); 523 | 524 | while((line1 != null)||(line2!= null)){ 525 | if(line1 != null){ 526 | pw.println(line1); 527 | line1 = br1.readLine(); 528 | } 529 | if(line2 != null){ 530 | pw.println(line2); 531 | line2 = br2.readLine(); 532 | } 533 | } 534 | 535 | pw.flush(); 536 | br1.close(); 537 | br2.close(); 538 | pw.close(); 539 | } 540 | } 541 | 542 | file 1 file2 543 | AAA 222 544 | BBB 333 545 | ccc 444 546 | 555 547 | 548 | AAA 549 | 222 550 | BBB 551 | 333 552 | CCC 553 | 444 554 | 555 555 | 556 | 557 | 558 | -------------------------------------------------------------------------------- /java_io~: -------------------------------------------------------------------------------- 1 | File I/O 2 | 3 | 1.File 4 | 2. FileWriter 5 | 3. FileReader 6 | 4. BufferedWriter 7 | 5. BufferedReader 8 | 4. PrintWriter 9 | 10 | File 11 | ___________ 12 | 13 | File f = new File("abc.txt"); 14 | this line won't create any physical file 1st it will check is there any physical file named with "abc.txt" is available or not if it is available then 'f' simply refers that file. If it is not available then we are just creating java file object to represent the name abc.txt. 15 | 16 | 17 | File f = new File("abc.txt"); 18 | 19 | sopln(f.exists()); false 20 | 21 | f.createNewFile(); 22 | 23 | sopln(f.exists()); true 24 | 25 | 1st run-----> false true 26 | 27 | 2nd run-----> true true 28 | 29 | we can use java file object to represent directory also. 30 | 31 | File f = new File("durga123"); 32 | 33 | sopln(f.exist());//false 34 | 35 | f.mkdir(); 36 | 37 | sopln(f.exist());//true 38 | 39 | 40 | Note: in unix every thing is treated as a file java file I/O concept is implemented based on Unix operating system. Hence java file Object can be used to represent both files and directories. 41 | 42 | File class Constructors 43 | __________________________ 44 | 45 | 1. File f = new File(String name); 46 | 47 | it creates a java file object to represent name of the file or directory in current working directory. 48 | 49 | 2. File f = new File(string subDirName, String name); 50 | 51 | it creates a java file object to represent name of the file or directory present in specified sub directory 52 | 53 | 3. File f = new File(File subDir, String name) 54 | 55 | same as above. 56 | 57 | e.g. 1. Write code to create a file name with abc.txt in current working directory. 58 | 59 | File f = new File("abc.txt"); 60 | f.createNewFile(); 61 | 62 | 2. Write code to create a directory named with "Durga123" in current working directory, and create a File name with "demo.txt" in that directory 63 | 64 | File f = new File("abc.txt"); 65 | f1.mkdir(); 66 | File f1 = new File("Durga123","demo.txt"); 67 | 68 | File f1 = new File(f, "demo.txt"); 69 | 70 | f1.createNewFile(); 71 | 72 | e.g 3.Write code to create a file named abc.txt in E:\xyz folder. 73 | 74 | File f = new File ("E://xyz", "abc.txt"); 75 | 76 | f.createNewFile(); 77 | 78 | Assume that E://xyz folder already available in out system. 79 | 80 | Important methods present in file class: 81 | _____________________________________________ 82 | 83 | 1. boolean exist(); Returns true if the specified file or directory available. 84 | 2. boolean createNewFile() : First this method will check whether the specified file is already available or not. If it is already available then this method returns false without creating any physical file. 85 | If the file is not already available then this method will creates new file and returns true. 86 | 3. boolean mkdir() : same as above. 87 | 88 | 4. boolean isFile() : Returns true if the specified file object pointing to physical file. 89 | 90 | 5. boolean isDirectory() : Returns true if f pointing to directory. 91 | 92 | 6. String[] list() : this method returns the names of all files and sub directories present in specified directory. 93 | 94 | 7. long length() : returns number of characters present in specified file. 95 | 96 | 8. boolean delete() : to delete specified file or directory 97 | 98 | Write a program to display the names of all files and directories present in C:/test 99 | 100 | import java.io.*; 101 | 102 | class Test{ 103 | public static void main(String[] args){ 104 | int count = 0; 105 | 106 | File f = new File("C:\\durga_classes"); 107 | String[] s = f.list(); 108 | for(String s1 : s){ 109 | count++; 110 | System.out.println(s1); 111 | } 112 | System.out.println("The total number : " + count); 113 | } 114 | } 115 | 116 | To display only file names : 117 | __________________________________ 118 | int count = 0; 119 | File f = new File("C://durgasoft"); 120 | String[] s1 = f.list(); 121 | 122 | for(String s1 : s){ 123 | File f = new File(s1); 124 | if (f.isFile()){ 125 | count++; 126 | sopln(f, s1); 127 | } 128 | } 129 | 130 | To display only Directory names: 131 | __________________________________ 132 | 133 | int count = 0; 134 | File f = new File("C://durgasoft"); 135 | String[] s1 = f.list(); 136 | 137 | for(String s1 : s){ 138 | File f = new File(s1); 139 | if (f.isDirectory()){ 140 | count++; 141 | sopln(f, s1); 142 | } 143 | } 144 | 145 | The above fileWriters ment for overriding of existing data. Instead of overriding if we want append operation then we have to create FileWriter by using the following constructors. 146 | 147 | 3. FileWriter fw = new FileWriter(String fileName, boolean append); 148 | 149 | 4. FileWriter fw = new FileWriter(File f, boolean append); 150 | 151 | Note : if the specified file is not already available then all the above constructors will create that file. 152 | 153 | 1. Write(int ch) to write a single character 154 | 155 | 2. Write(char[] ch) to write a array of characters. 156 | 157 | 3. write(String s) to write an string to the file 158 | 159 | 4. flush() to give guaranty that total data including last character will be return to the file. 160 | 161 | 5. close() to close the writer. 162 | 163 | FileWriter 164 | _______________ 165 | we can use fileWriter to write character data to the file 166 | 167 | Constructors: 168 | _____________ 169 | FileWriter fw = new FileWriter(String fileName); 170 | 171 | FileWriter fw = new FileWriter(File f); 172 | 173 | import java.io.*; 174 | 175 | class FileWriterDemo2{ 176 | public static void main(String[] args) throws IOException{ 177 | FileWriter fw = new FileWriter("abc.txt"); 178 | fw.write(100); 179 | fw.write("urg\nsoftwaresolutions"); 180 | fw.write('\n'); 181 | char[] ch1 = {'a','b','c'}; 182 | fw.write(ch1); 183 | fw.write('\n'); 184 | fw.flush(); 185 | fw.close(); 186 | } 187 | } 188 | 189 | output : 190 | durga 191 | softwaresolution 192 | abc 193 | 194 | In the above program fileWriter can perform overriding of existing data instead of overriding if we want append operation then we have to create fileWriter object as follows. 195 | 196 | FileWriter fw = new FileWriter("abc.txt", true); 197 | 198 | Note : The main problem with FileWriter is we have to insert line separator (\n) manually which is varied from System to System. It is difficulty to the programmer. We can solve this problem by using BufferedWriter and PrintWriter classes. 199 | 200 | FileReader 201 | _______________ 202 | We can use FileReader to read character data from file 203 | 204 | Constructors : 205 | 206 | 1. FileReader fr = new FileReader(String fileName); 207 | 2. FileReader fr = new FileReader(File f); 208 | 209 | Methods : 210 | 211 | 1. int read():it attempts to read next character from the file and returns its uni-code valueif next character not available then this method returns -1. As this method returns unicode value (int value), at the time of printing we have to perform typecasting. 212 | 213 | FileWriter fr = new FileWriter("abc.txt"); 214 | int i = fr.read(); 215 | while(i != -1){ 216 | soprint((Char)i); 217 | i = fr.read(); 218 | } 219 | 220 | 2. int read(char[] ch); 221 | 222 | It attempts to read enough characters from the file into char array. And returns number of characters copied from the file. 223 | 224 | File f = new File("abc.txt"); 225 | char[] ch = new Char[(int) f.length]; 226 | FR fr = new FR(f); 227 | fr.read(ch); 228 | 229 | for(Char ch1 : ch){ 230 | sopln(ch1); 231 | } 232 | 233 | 3. void close(); 234 | 235 | import java.io.*; 236 | 237 | class FileReaderDemo{ 238 | public static void main(String[] args){ 239 | File f = new File("abc.txt"); 240 | FileReader fr = new FileReader(f); 241 | char[] ch = new char[(int) f.length()]; 242 | fr.read(ch); 243 | for(char ch1 : ch){ 244 | System.out.print(ch1); 245 | } 246 | System.out.println("**************************"); 247 | FileReader fr1 = new FileReader("abc.txt"); 248 | int i = fr1.read(); 249 | while(i!= -1){ 250 | System.out.println((char)i); 251 | i = fr1.read(); 252 | } 253 | } 254 | } 255 | 256 | Note : By using FileReader we can read data character by character which is not convenient to the programmer. 257 | 258 | Usage of FileWriter and FileReader is not recommended because 259 | 260 | 1. while writing data by fileWriter we have to insert line seprator(\n) manually which is varied from System to system it is difficult to the programmer. 261 | 262 | 2. By using FileReader we can read data character by character, which is not convenient to the programmer. 263 | 264 | 3. To overcome these problems we should go for BufferedReader and BufferedReader. 265 | 266 | 4. BufferedWriter : we can use BufferedWriter to write character data to the file. 267 | 268 | Constructors : 269 | ________________ 270 | 271 | 1. BufferedWriter bw = new BufferedWriter(Writer w); 272 | 2. BufferedWriter bw = new BufferedWriter(Writer w, int BufferSize); 273 | 274 | Note : BufferedWriter can't communicate directly with the file. it can communicate via some Writer object. 275 | 276 | Q. Which of the following are valid 277 | 278 | 1. BufferedWriter bw = new BufferedWriter("abc.txt");//invalid 279 | 2. BufferedWriter bw = new BufferedWriter(new File("abc.txt"));//invalid 280 | 3. BufferedWriter bw = new BufferedWriter(new FileWriter("abc.txt"));//valid 281 | 4. BufferedWriter bw = new BufferedWriter(new BufferedWriter(new FileWriter("abc.txt"))); //valid 282 | 283 | 284 | Methods 285 | __________ 286 | 287 | 1. write(int ch) 288 | 2. write(char[] ch) 289 | 3. write(String s) 290 | 4. flush() 291 | 5. close() 292 | 6. newLine(); To insert a line separator. 293 | 294 | Q. When compared with the FileWriter which of the following capability available extra in method form in BufferedWriter. 295 | 296 | 1. Writing data to the file 297 | 2. close the file 298 | 3. flushing the file 299 | 4. inserting a new line character. 300 | 301 | import java.io.*; 302 | class BufferedWriterDemo{ 303 | public static void main(String[] args) throws IOException{ 304 | FileWriter fw = new FileWriter("abc.txt"); 305 | BufferedWriter bw = new BufferedWriter(fw); 306 | bw.writer(100); 307 | bw.newLine(); 308 | char[] ch1 = {'a','b','c','d'}; 309 | bw.write(ch1); 310 | bw.newLine(); 311 | bw.write("durga"); 312 | bw.newLine(); 313 | bw.write("Software solutions"); 314 | bw.flush(); 315 | bw.close(); 316 | } 317 | } 318 | 319 | output: 320 | 321 | d 322 | abcd 323 | durga 324 | SoftwareSolutions 325 | 326 | 327 | Note : Whenever we are closing BufferedWriter automatically internal FileWriter will be closed and we are not required to close explicitly. 328 | 329 | bw.close(); fw.close(); bw.close(); 330 | fw.close(); 331 | 332 | valid invalid invalid 333 | 334 | _____________________ 335 | BufferedReader 336 | _____________________ 337 | we can use BufferedReader to read character data from the file. 338 | The main advantage of BufferedReader when compared with FileReader is we can read data line by line in addition to character by character. 339 | 340 | Constructors 341 | _______________ 342 | 343 | 1. BufferedReader br = new BufferedReader(Reader r); 344 | 2. BufferedReader br = new BufferedReader(Reader r, int bufferSize); 345 | 346 | Note : BufferedReader can't communicate directly with the file and it can communicate via some Reader object. 347 | 348 | Methods 349 | _________ 350 | 1. int read(); 351 | 2. int read(char[] ch) 352 | 3. void close(); 353 | 4. String readLine(); It attempts to read next line from the file and returns it. If the next line not available then this method returns null. 354 | 355 | import java.io.*; 356 | 357 | class BufferedReaderDemo{ 358 | public static void main(String[] args) throws IOException{ 359 | FileReader fr = new FileReader("abc.txt"); 360 | String line = br.readLine(); 361 | while(line != null){ 362 | System.out.println(ln); 363 | line = br.readLine(); 364 | } 365 | br.close(); 366 | } 367 | } 368 | 369 | Note : Whenever we are closing BufferedReader automatically underlying FileReader will be closed and we are not required to close explicitly. 370 | 371 | Note : The most enhanced reader to read character data from the file is BufferedReader. 372 | 373 | _____________ 374 | PrintWriter 375 | _____________ 376 | 377 | It is the most enhanced writer to write character data to the file. The main advantage of PrintWriter over FileWriter and BufferedWriter is we can write any type of primitive directly to the file 378 | _____________________ 379 | Constructors : 380 | _____________________ 381 | 382 | 1. PrintWriter pw = new PrintWriter(String fileName); 383 | 2. PrintWriter pw = new PrintWriter(File f); 384 | 3. PrintWriter pw = new PrintWriter(Writer w); 385 | 386 | Note : PrintWriter can communicate with directly with the file and can communicate via some writer object also. 387 | 388 | Methods : 389 | __________ 390 | 391 | 1. write(int ch) 392 | 2. write(String s) 393 | 3. write(Char[] ch) 394 | 4. flush(); 395 | 5. close(); 396 | 397 | print(char ch); 398 | print(int i); 399 | print(double d); 400 | print(String s); 401 | ............ 402 | 403 | println(char ch); 404 | println(int i); 405 | println(double d); 406 | println(String s); 407 | ............ 408 | 409 | class PrintWriterDemo1{ 410 | public static void main(String[] args) throws IOException{ 411 | FileWriter fw = new FileWriter("abc.txt"); 412 | PrintWriter out = new PrintWriter(fw); 413 | out.write(100); 414 | out.println(100); 415 | out.println(true); 416 | out.println('c'); 417 | out.println("durga"); 418 | out.flush(); 419 | out.close(); 420 | } 421 | } 422 | 423 | output: 424 | 425 | d100 426 | true 427 | c 428 | durga 429 | 430 | Q. What is the difference between write(100) and print(100). 431 | 432 | Ans. In the case of write(100) the corresponding character d will be added to the file but in the case of print(100) the int value 100 will be added to the file directly. 433 | 434 | Note : the most enhanced writer to write character data to the file is PrintWriter where as the most enhanced reader to read character data from the file is BufferedReader. 435 | 436 | 437 | 438 | Note : In general we can use Readers and Writers to handle character data(text data), where as we can use streams to handle binary data(like images, PDF files, Video files, Audio files etc.) 439 | 440 | we can use outputStream to write Binary data to the file, inputStream to read Binary data from the file. 441 | 442 | Object 443 | /\ 444 | / \ 445 | / \ 446 | / \ 447 | / \ 448 | / \ 449 | / \ 450 | / \ 451 | / \ 452 | / \ 453 | Writer(ac) Reader(AC) 454 | /|\ / \ 455 | / | \ / \ 456 | / | \ / \ 457 | / | \ / \ 458 | / | \ / \ 459 | / | \ / \ 460 | / | \ / \ 461 | / | \ / \ 462 | / | \ / \ 463 | Output Buffered Print Input BufferedReader 464 | Stream Writer Writer Stream 465 | Writer Reader 466 | | | 467 | | | 468 | | | 469 | | | 470 | FileWriter FileReader 471 | 472 | 473 | Q. Write a program to Merge a data from two files in a third file. 474 | 475 | 476 | import java.io.*; 477 | 478 | class FileMerger{ 479 | public static void main(String[] args)throws IOException{ 480 | PrintWriter pw = new PrintWriter("File3.txt"); 481 | BufferedReader br = new BufferedReader(new FileReader("file1.txt")); 482 | String line = br.readLine(); 483 | while(line != null){ 484 | pw.println(line); 485 | line = br.readLine(); 486 | } 487 | br = new BufferedReader(new FileReader("File2.txt")); 488 | line = br.readLine(); 489 | while(line != null){ 490 | pw.println(line); 491 | line = br.readLine(); 492 | } 493 | pw.flush(); 494 | br.read(); 495 | pw.close(); 496 | } 497 | } 498 | 499 | aaa 222 500 | bbb 333 501 | ccc 444 502 | 555 503 | 504 | aaa 505 | bbb 506 | ccc 507 | 222 508 | 333 509 | 444 510 | 555 511 | 512 | 513 | 514 | 515 | 516 | 517 | --------------------------------------------------------------------------------