Core Java
What is Java? Java is a internet software developed by Sun Microsystems for development of distributed applications. What is software? Is a set of programs meant for performing some specific operation in real world we have 3 types of software they are. Types of java application Standalone Application Web Application Enterprise Application Mobile Application Features and Buzzwords of Java Sun Microsystems has provided 13 features for java language 1. Simple 2. Platform Independent 3. Architectural neutral 4. Portable 5. Multithread 6. Networked Programming Language 7. Distributed Programming Language 8. High Performance 9. High Interpreted 10. Secured 11. Robust(Strong) 12. Dynamic 13. OOPL.................... Features of a language are nothing but the services or facilities provided by language vendor to the industry programmer.
Core Java
1) Simple: 2) Java is simple programming language because of the following factors. a) Java programming language eliminates a complex concept called pointers hence we are able to develop the application with less time and it will take less execution time because of magic of Byte code. 3) Let us consider the following Diagram 4)
5) Byte Code: Byte code is set of optimized instructions generated during compilation phase by the java compiler and nature of byte code is so powerful than ordinary pointer code. 6) JVM: JVM is set of programs developed by sun Microsystems and supplied as a part of JDK and its role is reading line by line of byte code and converting into native understanding form of OS. 7) Note: Byte code is OS independent and JVM is OS dependent. 8) JIT (Just in time compiler): JIT is a program developed by sun Microsystems added as a part of JVM to speed up the interpretation phase by reading the entire section of byte code.“Java is one of the compiler and interpretation based prog lang” 9) 10) b) Java programming environment contains inbuilt garbage collector program. 11) Garbage Collector: Is a system background java program which is running along with our regular java program for collecting un-used/un-reference memory space and it improves the performance if java application. 12) Garbage program is internally running for regular intervals of time. 13) 14) Platform Independent: The language/technology related application are said to platform independent if and only if those application run on every OS without considering their providers / vendors. 15) In order to say a language / technology are platform independent, it has to satisfy the following properties. 16) a) The data types of the language must take the same amount of memory space on all OS. b) The language / technology must contains some special powerful internal programs which will convert the native understanding form of one OS to the native understanding form of another OS. 17) Architecture Neutral: Java’s byte code is not machine dependent. It can run on any machine with any processor and any operating system. 18) Portable: Java does not have implemented-dependent aspects. So the results will be same on all machine, portable means yielding same results on different machines.
Core Java
19) Multithreading: The basic aim of multithreading is to achieve the concurrent execution. A flow of control in java is known as thread. The purpose of thread concept is to execute user define method which contains the logic of the java program. If any java program contains multiple flow of controls then that java program is known as multithreaded. The language like C, C++, Pascal, COBOL etc come under single threaded modelling language because their execution environment contains single flow of control. In general single threaded modelling language provides sequential execution but not concurrent execution and they not contain any library for development of multithreaded application. The language like Java and .Net are threaded as multithreaded because their execution environment provides and contains multiple flow of controls. In Java programming we have the following API for development of multithreading application Java.lang.Thread(class). Java.lang.Runnable(Interface). 20) Whenever we write a java program 2 types of threads exist 1) Fore-ground / child thread. 2) Back-ground / parent thread. 21) “Multitasking concept of java is one of the specialized form of multitasking concept of OS. 22) Networked: To share the data between multiple machines which are located either in same network or in different network, Intranet application will be developed by J2SE with network programming concept. 23) Distributed: According to real world project, java project are classified into 2 types i. Centralized Application. ii. Distributed Application. i) Centralized application: Centralized application are those which runs in the context of single server and their result can be accessible across the globe and they are operated by authorized people only. (Banking , insurance ...) ii) Distributed application: which runs in the context of multiple servers and result are accessible across the globe and they are operated by both authorized and unauthorized user. 24) Note: Centralized application will have private URL. 25) Distributed application will have public URL. 26) High Performance: Java is one of the high performance programming language because of the following factors i. Automatic memory management due to inbuilt garbage collector. ii. Java is free from pointers. iii. Due to JIT which enhances the speed of the execution. 27) Robust: The language like Java and .Net are threaded as Robust/Strong programming language because Runtime error are effectively addresses by the concept called Exception Handling. OR java programs will not crash because of its exception handling and its memory management features.
Core Java
28) Highly Interpreted: In the older version of java (JDK 1.0) compilation phase was very faster and interpretation phase was very slow this is one the industry programmer complimented and compliant to sun Microsystems. 29) Sun Microsystems has taken this task as challenging issue and they developed a program called JIT and added as part of JVM to speed up the interpretation phase by reading entire section of byte code at once. 30) Secure: Security is one of the principal in IT world for preventing / protecting the unauthorized modification on confidential data. The language like Java and .Net are treated has high secured programming language because their API contains readily available security programs in a package called javaX.security.*; 31) Dynamic: In any programming language, if we write a program and that program accepts input then the input of program is stored in the main memory by allocating sufficient amount of memory space. 32) In any programming language memory allocation can be done in 2 ways i. Static Memory Allocation. ii. Dynamic Memory Allocation. 33) i) Static Memory Allocation is one in which memory will be allocated for the impact of the program at compile time because of static Memory allocation we get the following drawbacks a. Waste of memory space. b. Loss of Data. c. Overlapping of Existing Data. ii) Dynamic Memory Allocation is one in which memory will be allocated for the input of the program at run time . o Java follows only dynamic memory allocation but not static memory allocation. o To allocate the memory space dynamically is java programming we use operator called new. 34) 35) Object Oriented Programming: Main Feature we will discuss further
Core Java 36) What is the architecture of JVM? 37)
38) diagram.
JVM has various sub components internally. You can see all of them from the above
1. Class loader sub system: JVM's class loader sub system performs 3 tasks a. It loads .class file into memory. b. It verifies byte code instructions. c. It allots memory required for the program. 2. Run time data area: This is the memory resource used by JVM and it is divided into 5 parts a. Method area: Method area stores class code and method code. b. Heap: Objects are created on heap. c. Java stacks: Java stacks are the places where the Java methods are executed. A Java stack contains frames. On each frame, a separate method is executed. d. Program counter registers: The program counter registers store memory address of the instruction to be executed by the micro processor. e. Native method stacks: The native method stacks are places where native methods (for example, C language programs) are executed. Native method is a function, which is written in another language other than Java. 3. Native method interface: Native method interface is a program that connects native methods libraries (C header files) with JVM for executing native methods.
Core Java 4. Native method library: holds the native libraries information. 5. Execution engine: Execution engine contains interpreter and JIT compiler, which covert byte code into machine code. JVM uses optimization technique to decide which part to be interpreted and which part to be used with JIT compiler. The Hotspot represents the block of code executed by JIT compiler. 39) Java memory management 40) Java Heap Memory v/s Stack Memory 41) Java Heap Memory 42) This is the memory where the Objects and JRE classes are stored at the runtime. When the object is created it is stored in the heap. Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application. In multithreading the objects are available for all the threads, means all the threads share the same heap 43) Java Stack Memory 44) Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory. 45)
46) public class Memory { 47) 48) public static void main(String[] args) { // Line 1 49) int i=1; // Line 2 50) Object obj = new Object(); // Line 3 51) Memory mem = new Memory(); // Line 4 52) mem.foo(obj); // Line 5 53) } // Line 9 54) 55) private void foo(Object param) { // Line 6 56) String str = param.toString(); // Line 7 57) System.out.println(str); 58) } // Line 8 59) 60) }
Core Java 61)
When we run a program it loads all the runtime class into the heap space The main method is found at the Line-1 now the memory for the main method is allocated in the stack region by the main thread. We are creating the local variables at Line-2 it is going to be created in the stack region of main block. In Line-3 we are creating the object the object is going to be created in the heap region and its reference is stored in the stack region, similarly in Line-4 we are creating one more object. In Line-5 we are calling the method foo( ) than the memory for the method is going to be allocated in the stack region ( the block of memory is going to be allocated in the stack region). Since java is pass by value the one more reference is created at the Line-6 From the foo( ) method we are creating one more String object it is going to be created in the heap region, the reference is present in the stack region inside the stack. ( String objects are going to be created in the String pool in the heap) Has soon has the control reach Line-8 the method looses the scope, than the memory that was allocated to the method foo( ) becomes free When the Line-9 is executed than the main method also going to loose the scope, and the memory allocated to it also get free. Than java runtime will free al the memory allocated and the execution completes.
62) 63) Difference between Heap v/s Stack Objects stored in the heap are globally accessible whereas stack memory is not accessed by other threads . Heap is the place where objects are stored, the stack region is the place where the local variables are stored and the reference to the objects that are stored in heap region. Stack memory is short lived where has heap memory is going to exists till the end of application execution. When stack memory is full it throws java.lang.StackOverFlowError , where has if heap memory is full java.lang.OutOfMemoryError Stack memory is very less when compared to Heap Stack is very fast when we compared to Heap 64) How to set a path of JDK? 65)
Set path=C:\Program Files\Java\jdk1.7.0_45\bin
Core Java 66) How to change the driver?
Step1 C:\User\Vikas> cd.. Step2 C:\>d: Step3 D:\>
67) How to create a folder?
Step1 Step2 Step3
D:\> mkdir NewFolderName D:\NewFolderName>mkdir OtherFolder D:\NewFolderName\OtherFolder>
68) How to create a java file?
Step1 D:\NewFolderName\OtherFolder> notepad FileName.java 69) (if the notepad does not open than open notepad and save it inside a folder (OtherFolder) and save with .java extension
70) How to compile a java program?
Step1 Step2
D:\NewFolderName\OtherFolder>javac FileName.java D:\NewFolderName\OtherFolder>java FileName
71) 72) 73) Data type 74) A data type is a classification of the type of data that a variable can hold in computer programming. 75) Data types in Java are classified into two types: 1. 2.
Primitive—which include integer, character, boolean, and floating Point type values. Non-primitive—which include Classes, Interfaces, Object type and Arrays. 76) 77) Primitive Data Types: 78) 79) There are eight primitive data types supported by Java. 80) 81) byte: data type is an 8-bit value from -128 to 127 (27 to 27-1) default value is 0 82) short: data type is an 16-bit value from -32,768 to 32,767 (215 to 215-1) default value is 0 83) int: data type is an 32-bit value from - 2,147,483,648 to 2,147,483,647 (231 to 231-1) default value is 0 84) long: data type is an 64-bit value from (263 to 263-1) default value is 0L 85) float:
Core Java data type is an 32-bit Float is mainly used to save memory in large arrays of floating point numbers default value is 0.0f 86) double: data type is an 64-bit This data type is generally used as the default data type for decimal values, generally the default choice default value is 0.0 87) boolean: it represents one bit of information it can contain only true or false ( no 1 or 0 is allowed ) default value is false 88) 89) char: its sixe is 16 bit it is used to store only one character default value is space ( we represent it by 0) 90) 91) Variables 92) A variable is the one which holds some value which can be altered later in the program. Or it is the named storage which can be altered later in the program. 93) int i; //declaration 94) i = 20; // initialisation
95)
Methods
Methods are the one which contains group of statements, which are used to perform some functionality. Which are called by using their names. Methods contains group of statements A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name It increase the readability and reusability of code In java we call functions has methods, because hear the methods can be written only inside class but not outside the class has in C++ Methods are used to tell the behaviour of the object Syntax 96) (arguments) 97) { 98) // Body of method 99) //return keyword with returning value 100) } 101)
Example 102) 103) 104) 105) 106)
int add() { return 5+6; }
Core Java 107) In the above example the add() method returns 11, which of type int 108) 109) void drink() 110) { 111) System.out.println("Drinking water.....!"); 112) } 113) 114) In the above example the drink() method will not return anything so the return type is void. 115)
Note:
If we specify any return type while declaring than that method should return that type value. The return statement word should be present at the last. In the séance the return statement should be logically the last line in the method block If the return type is void means we need not to specify the return statement at the last. Compiler itself is going to write the return statement. If at all if you need to specify means do has below.(a empty return statement) void drink() 116) { 117) System.out.println("Drinking water.....!"); 118) return; 119) } the method can have empty return statement, if the return type of the method is void. But that return statement should not even return 0(zero) , ‘ ’(space) or null Advantage is code reusability There are two types of methods Static methods Non-Static methods Static methods : These methods a declared using the static key word o Example 120) void static method1() 121) { 122) System.out.println("In method1() its a static method.....!"); 123) } Static method can be accessed directly by just using the class name. From static methods we cant accesses non static members directly o Example : 124) class AddingMethod 125) { 126) static void add(int i , int j) 127) { 128) System.out.println("Addition of two numbers......"); 129) int sum=0; 130) sum = i + j; 131) System.out.println("Sum of "+i+" and "+j+" is = "+sum); 132) } 133) void sub(int m , int n) 134) {
Core Java 135) System.out.println("Addition of two numbers......"); 136) int diff = 0; 137) diff = m - n; 138) System.out.println("Difference of "+n+" from "+m+" is = "+diff); 139) } 140) } 141) class MethodMember 142) { 143) public static void main(String args[]) 144) { 145) AddingMethod.add(50,60); // static method is called by class name 146) AddingMethod.sub(150,60); //Error sub is non-static 147) } 148) } Non-static methods : These methods are declared without static keyword. Non-static methods can accesses static members directly o Example 149) void method2() 150) { 151) System.out.println("In method1() its a non-static method.....!"); 152) } Non-static members are called by creating the instance of the class or by using the object reference of the class 153) 154) o Example 155) 156) class MethodMember 157) { 158) public static void main(String args[]) 159) { 160) AddingMethod.add(50,60); // static method is called by class name AddingMethod ref1 = new AddingMethod(); 161) ref1.sub(150,110); // non-static method can be called only using reference 162) AddingMethod ref2 = new AddingMethod(); 163) ref2.add(80,20); // static method can be also called by using reference 164) } 165) } 166) class AddingMethod 167) { 168) static void add(int i,int j) 169) { 170) System.out.println("Addition of two numbers......"); 171) int sum=0; 172) sum = i + j; 173) System.out.println("Sum of "+i+" and "+j+" is = "+sum); 174) }
Core Java
175) void sub(int m , int n) 176) { 177) System.out.println("Addition of two numbers......"); 178) int diff = 0; 179) diff = m - n; 180) System.out.println("Difference of "+n+" from "+m+" is = "+diff); 181) } 182) } 183) Static members 184) Non-Static members 185) static members are also known has Class 186) non-static members are also known has members Object members 187) static members are loaded only once for 188) non-static members are loaded for every entire program execution instance of class 189) If static members are changed it gets 190) if a non-static members of an instance is changed for entire program changed that change will not reflect in other instance of class 191) static members can be used across any 192) non-static members cannot be shared objects across the Object 193) static members are loaded into heap by 194) non-static members are loaded into heap class loader when JVM encounter Object creation statement 195) all static members reside in common area 196) non-static member are loaded into Obje known has static pool memory after object creation 197) static members are accessed through class 198) non-static members are accessed by usin name the reference variable 199) 200)
Core Java
201) Class 202) A class is the blueprint from which individual objects are created. Class is a one which contains states (variables) and behaviour (methods) 203) 204) Syntax – 205) class 206) { 207) //code 208) } 209) 210) public class Lover 211) { 212) 213) 214) 215) 216) 217) 218) 219) 220) 221) 222) 223) 224) 225) 226) 227) 228) 229)
String name; int age; char sex; double height;
//state //state //state it takes only M or F //state
void takeToPark() //behaviour { System.out.println("Take in a R-15"); } int spendMoney() {
//behaviour
int money=5000; return money; } } Object
230) An object is an instance of a class. The term ‘object’, however, refers to an actual instance of a class. Every object must belong to a class. 231) 232) class. 233) 234) 235) 236) 238) 239) 240) 241) 242)
Note Objects have a lifespan but classes do not Object of a calss can be created using the new keyword and name of the new ; public class Test { public static void main(String[] args) 237) { Lover l1 = new Lover(); Lover l2 = new Lover(); } } 243)
Core Java 244)
Core Java
245) 246)
OOPS CONCEPTS
Inheritance
247) It is one of the oops concept of java. Inheritance means, it’s a mechanism where the child class acquires the properties of the parent class or supper class. 248)
Example :
249) 250) 251) 252) 253) 254) 255) 256) 257) 258) 259) 260) 261) 262)
class Boy { String name; int age; void factory() { System.out.println("factory() method of boy"); } void banglo() { System.out.println("banglo() method of boy"); }
263)
}
264) 265) 266)
class Girl extends Boy { double height; String colour;
267) 268) 269) 270) void job() 271) { 272) System.out.println("job() method of Girl"); 273) } 274) 275) void prepareFood() 276) { 277) System.out.println("prepareFood() method of Girl"); 278) } 279) 280) void details() 281) { 282) System.out.println("Name "+name+" age is "+age+" height is "+height+" and colour is "+colour); 283) } 284) } 285) 286) class InheritanceProgram 287) {
Core Java 288) 289) 290) 291) 292) 293) 294) 295) 296) 297) 298) 299) 300)
public static void main(String args[]) { Girl ref = new Girl(); ref.name="reka"; ref.age=20; ref.factory(); ref.banglo(); ref. height =5.5; ref.colour="pink";
301) }
302) 303) 304) 305) 306) 307) 308) 309) 310) 311) 312) 313) 314)
ref.job(); ref.prepareFood(); ref. details();
} OutPut C:\Users\Vikas\Desktop\java>javac InheritanceProgram.java C:\Users\Vikas\Desktop\java>java InheritanceProgram factory() method of boy banglo() method of boy job() method of Girl prepareFood() method of Girl Name reka age is 20 height is 5.5 and colour is pink
315) 316) In the above example we see the single level inheritance, hear the Girl class inherit all the properties of Boy class . The name, age , factory(), bangle() of Boy class is acquired by the Girl class, so by creating the object of Girl class I can accesses both the Boy class and Girl class properties. 317)
318) 319)
java supports inheritance there are many types of in heritance o single inheritance ( above example ) o multilevel inheritance
Core Java o
hierarchical inheritance
320) 321)
Example for multilevel inheritance
322)
class Parent
323)
{
324)
}
325)
class Boy extends Parent
326)
{
327)
}
328)
class Girl extends Boy
329)
{
330)
}
331) In the above example the Boy class can acquire the properties of Parent class, mean while has Girl class extends Boy class, so a Girl class can acquire the properties of both the Parent class and the Boy class. 332)
333) 334) 335) 336)
Core Java 337)
Example for hierarchical inheritance
338)
339) Note : Java does not support the multiple inheritance where has it only supports multilevel inheritance. 340)
341) If class A and class B have same methods than the class C will be in confusion to take the method from which class so this concept was ruled out in java. 342) If you create the Object of class C than the constructor is called, hear that constructor will execute the super statement, here again there is a confusion which is parent class and whose constructor is need to be called
Core Java 343)
IS-A Relationship
This refers to inheritance or implementation. Expressed using keyword “extends”. Main advantage is code reusability. 344) 345) 346) class Animal 347) { 348) void walk() 349) { 350) System.out.println("Walk"); 351) } 352) void eat() 353) { 354) System.out.println("eat food"); 355) } 356) } 357) 358) class Cow extends Animal //Cow is-a Animal 359) { 360) void giveMilk() 361) { 362) System.out.println("cow give milk"); 363) } 364) void sound() 365) { 366) System.out.println("ambaa...ambaaa"); 367) } 368)} 369) 370) class Dog extends Animal //Dog is-a Animal 371) { 372) void sound() 373) { 374) System.out.println("bow...bow"); 375) } 376) } 377) public class Test { 378) public static void main(String[] args) { 379) Animal a = new Cow(); 380) a.walk(); 381) a.eat(); 382) 383) a.giveMilk(); //not possible Parent reference cant accesses child member 384) 385) a.sound(); //not possible Parent reference cant accesses child member 386) 387) Dog d = new Animal(); //not possible because child reference cannot be give to Parent object 388) 389) Cow c = new Cow(); 390) c.walk(); 391) c.eat(); 392) c.sound(); 393) c.giveMilk();
Core Java 394) 395) 396)
} }
Whatever the parent class has, is by default available to the child. Hence by using child reference, we can call both parent and child class methods.
Whatever the child class has, by default is not available to parent, hence on the parent class reference we can only call parent class methods but not child specific methods.
Parent class reference can be used to hold child class objects , but by using that reference we can call only parent class methods but not child specific methods.
We cant use child class reference to hold parent class objects 397)
HAS-A Relationship
Has-A means an instance of one class “has a” reference to an instance of another class or another instance of same class.
It is also known as “composition” or “aggregation”.
There is no specific keyword to implement HAS-A relationship but mostly we are depended upon “new” keyword. 398) 399) 400) 401) 402) 403) 404) 405) 406) 407) 408) 409) 410) 411) 412) 413) 414) 415) 416) 417) 418) 419) 420) 421) 422) 423) 424) 425) 426) 427) 428) object 429) object
class Mobile { void giveCall() { //some code } void playGame() { //some code } } class Person { Mobile m = new Mobile(); //So we can tell person has a Mobile void eatFood() { //some code } void drinkWater() { //some code } } public class Test { public static void main(String[] args) { Person p = new Person(); p.m.giveCall(); //Person has a mobile so accessing it using person p.m.playGame(); //Person has a mobile so accessing it using person
Core Java 430) 431)
} }
Core Java 432)
Variables
433) 434)
435) Local Variables 436) Any variables declared inside a method or constructor is called has local variables. Local variables need to be initialised before they are used. Local variables do not have default value. 437) 438) Global Variables 439) Any variables declared inside the class but outside the methods or constructors are called has global variables. Global variables will take a default if u have not initialised it. 440) Instance variables the global variables declared without static keyword is called has instance variables. These variables get initialised whenever the object is created. 441) Instance variables are one for the object. 442) Static variables the global variables declared with the static keyword are called has static variables. These variables will get initialized whenever the class loads into memory. These variables are one for the class. 443) 444) An argument is an expression passed to a function or constructor, where a parameter is a reference declared in a function declaration or even constructor. 445) class Gift { 446) 447) void buy(String name , int cost) parameters 448) { 449) //some code hear 450) } 451) void Gift(double d , char c)
//name and cost r called has formal
//d and c are called has formal parameters
Core Java 452) 453) 454) 455) 456) 457) 458) 459) 460) 461) 462)
{ //some code }
public static void main(String[] args) { double e = 5.5; char v = ‘M’; Gift g = new Gift(e , v); //e and v are the actual arguments 463) 464) String hesaru = "barby"; int money = 200;
465) 466)
467) 468) 469)
g.buy(hesaru , money); //hesaru and money are the actual arguments }
}
470) 471)
472) Constructor
Constructor is special kind of method which gets called when object is created Constructor don’t have return type Constructor cannot be inherited Constructor name is same has the class name Every class should have a constructor, if we don’t write a constructor compiler will write a default constructor. Compiler will not write a default constructor, if we are going to write any of the constructor explicitly Constructor with no parameters or a zero parameter constructor is called has default constructor Constructor with parameter is called has parameterized constructor. These constructor is used to initialise the instance variables at the time of creating object Syntax 473) ClassName ( ) 474) { 475) //some code… 476) } 477) 478) Eg :- class Cow 479) { 480) //zero parameter constructor of Cow Class 481) public Cow() 482) { 483) System.out.println("I am in Cow class constructor.....!"); 484) } 485) }
Core Java 486) Note : If you don’t write any constructor inside a class by default there will be a default constructor inside that class, and that default constructor will be similar like a zeroparameterized constructor. Zero parameterized constructor is also called has default constructor. 487) 488)
Core Java 489)
class Cow 490)
{
491)
//zero parameter constructor of Cow Class
492)
public Cow()
493)
{
494)
System.out.println("I am in Cow class constructor.....!");
495)
}
496)
}
497)
class Test1
498)
{
499)
public static void main(String[] args)
500)
{
501)
System.out.println("Before creating object");
502)
Cow ref = new Cow();
503)
System.out.println("After creating 1st object");
504)
new Cow();
505)
System.out.println("After creating 2nd object"); 506) 507)
508)
// when this line is executed again the Cow() constructor is called
}
}
Output : 509) 510) 511) 512) 513)
514) 515)
//when this line is executed the Cow() constructor is called
Before creating object I am in Cow class constructor.....! After creating 1st object I am in Cow class constructor.....! After creating 2nd object
Core Java 516) Constructor Over Loading 517) A class can contain more than one constructor inside it, but they should vary with number of parameters or type of parameters. This concept is called has contractor overloading. 518) 519) 520) 521) 522) 523) 524)
class Cow { public Cow() { System.out.println("I am in Cow() constructor.....!"); } 525)
526) 527) 528) 529)
public Cow(int leg) { System.out.println("I am in Cow(int leg) constructor.....!"); }
530)
public Cow(double height) 531) { 532) System.out.println("I am in Cow(double hight) constructor.....!"); 533) } 534) 535) public Cow(int ears , int mouth) 536) { 537) System.out.println("I am in Cow(int ears , int mouth) constructor.....!"); 538) } 539) } 540) 541) These constructors can be called by creating a object like 542) 543)
new Cow();
544)
new Cow(4.5); // Cow(double height) constructor is called 545) 546)
547)
// Cow() constructor is called
new Cow(2,1); // Cow(int ears , int mouth)constructor is called new Cow(4);
// Cow(int leg) constructor is called
Note : The parameterized constructor is used to initialize the instance variables of the class If you don't define a constructor, the default constructor (which has no parameters) will be generated by default. If you have any user-defined constructor, the default constructor will not be generated at all.
548) 549)
this key word
this is a keyword in java which refers to the current class object
Core Java
if there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity this keyword refers to current class instance variables
550) 551) Example : 552) class SweetHeart 553) { 554) String name; 555) int age , salry; 556) double hight; 557) 558) SweetHeart(String name , double hight , int age , int salry) 559) { 560) this.name=name; 561) this.hight=hight; 562) this.age=age; 563) this.salry=salry; 564) } 565) void detailsOfAge() 566) { 567) System.out.println("My sweetHeart name is "+name+" and the age is "+age); 568) } 569) void fullDetails() 570) { 571) System.out.println("My sweetHeart name is "+name+" and the age is "+age+" hight is "+hight+" and get a salry rs "+salry); 572) } 573) } 574) 575) class Test2 576) { 577) public static void main(String[] args) 578) { 579) SweetHeart ref1=new SweetHeart("Geetha",4.9,20,15000); 580) ref1.fullDetails(); 581) 582) SweetHeart ref2=new SweetHeart("Ramesh",5.5,18,20000); 583) ref2.fullDetails(); 584) 585) //To print only name and age call detailsOfAge() 586) 587) ref1.detailsOfAge(); 588) ref2.detailsOfAge(); 589) 590) } 591) } Try this program and write the output. Pleas practice more programs on all topics 592)
Core Java 593)
Core Java 594) 595) 596) 597) 598) 599) 600)
Note : class SweetHeart { String name; int age,salry; double hight;
601) SweetHeart(String name , double hight , int age , int salry) 602) { 603) name=name; 604) hight=hight; 605) age=age; 606) salry=salry; 607) } 608) } 609) Hear the local variables get more priority so the instance variables will not get a scope to get initialize, 610) name (local variable) is different than the name (instance variable). So we make use of this keyword to initialize the instance variables of the class, when both local and instance variables name is same. 611) class Test 612) { 613) 614) 615) 616)
Test() { return ; } 617) 618)
} This example will compile and run. But return keyword should not return any
value 619) 620)
Constructor chaining
In Java you can call one constructor from another and it’s known as constructor chaining in Java. We can call the same class constructor using this key word this( ) must be the 1st line inside a constructor 621) Example : 622) class Bus 623) { 624) Bus() 625) { 626) this("Banglore"); //this(“Banglore”) will call Bus(String name) 627) System.out.println("Bus is empty.....!"); 628) } 629)
Core Java 630) 631) 632) 633) 634) 635)
Bus(String name) { this(10); //this(10) will call Bus(int num) System.out.println("Bus is having a name.....!"); } 636)
637) 638) 639) 640) 641) 642)
Bus(int num) { System.out.println("Bus is having a NUMBER.....!"); }
} class ConstructorChaining {
643) 644) 645) 646) 647) } Output : 648) 649) 650)
public static void main(String[] args) { new Bus(); }
Bus is having a NUMBER.....! Bus is having a name.....! Bus is empty.....!
We can call the parent (super) class constructor by using super key word 651) super( ) is used to call the immediate parent class constructor. super( ) must be the 1 st line in constructor Example : 652) class Train 653) { 654) Train() 655) { 656) this("Hassan"); //this(“Hassan”) will call Train(String name) 657) System.out.println("Train is empty.....!"); 658) } 659) Train(String name) 660) { 661) this(55); //this(10) will call Train(int num) 662) System.out.println("Train is having a name.....!"); 663) } 664) Train(int num) 665) { 666) System.out.println("Train is having a NUMBER.....!"); 667) } 668) } 669) class Bus extends Train 670) { 671) Bus() 672) {
Core Java 673) name) 674) 675) 676) 677) 678) 679) 680) 681) 682) 683) class 684) 685)
this("Banavara");
System.out.println("Bus is empty.....!"); } Bus(String name) { this(10); //this(10) will call Bus(int num) System.out.println("Bus is having a name.....!"); } Bus(int num) { super();//super() will call Train() because Train is parent System.out.println("Bus is having a NUMBER.....!"); 687) 688)
689) 690) 691) 692) 693) 694) 695) 696) 697) 698) 699) 700) 701) 702)
//this(“Banglore”) will call Bus(String
} 686) } class ConstructorChaining { public static void main(String[] args) { new Bus(); } }
OutPut : Train is having a NUMBER.....! Train is having a name.....! Train is empty.....! Bus is having a NUMBER.....! Bus is having a name.....! Bus is empty.....! Note :
703)
Constructor chaing should not lead to recursion.
704)
Example:
705)
class Bus extends Train 706)
{
707)
Bus()
708)
{
709)
this("Banavara");
710)
System.out.println("Bus is empty.....!");
711)
}
712)
Bus(String name)
713)
{
Core Java 714)
this(10);
715)
System.out.println("Bus is having a name.....!");
716)
}
717)
Bus(int num)
718)
{
719) recursion
this(); // Hear the error occurs because it is leading for
720)
System.out.println("Bus is having a NUMBER.....!");
721)
} 722)
}
723) super( ) and this( ) cannot be present inside the same constructor. Any one can be present inside. 724) 725)
Bus(int num) {
726)
this();
727)
super(); //Error because super( ) must be 1st line
728)
System.out.println("Bus is having a NUMBER.....!");
729) 730) 731)
} Bus(int num) { 732)
super();
733)
this(); //Error because this( ) must be 1st line
734) 735) 736)
System.out.println("Bus is having a NUMBER.....!"); }
Core Java 737)
Instance-Init Block (non-static block)
738) 739) 740) 741) 742) 743) 744) 745) 746) 747) 748) 749) 750) 751) 752) 753) 754) 755) 756) 757) 758) 759) 760) 761) 762)
768)
769) 770) 771) 772) 773)
Instance block will execute whenever a new object is created. If there are more than one instance block than it will execute in the sequence of the order they are written These are used to declare the instance variables of the class class Run1 { //instance block { System.out.println("In INIT block of Run1"); } } class Run2 { //instance block { System.out.println("In INIT block of Run2"); } } class Test1 { public static void main(String[] args) { new Run1();//Now the instance blcok of Run1 class will execute System.out.println("1st instance block is created.......!"); new Run2();//Now the instance blcok of Run2 class will execute } } OutPut 763)
D:\bin>javac Test1.java
764)
D:\bin>java Test1
765) In INIT block of Run1 766) 1st instance block is created.......! 767) In INIT block of Run2 Static Block It's a block of code which is executed when the class gets loaded by a class loader. It is meant to do initialization of static members of the class. static block executes once in life cycle of any program another property of static block is that it executes before main method Static blocks are also called Static initialization blocks
class Test1 { static
Core Java 774) 775) 776) 777) 778) 779) 780) 781) 782) 783) 784) 785) 786) 787)
805)
{ System.out.println("In Test1 static block"); } } class Demo1 { public static void main(String[] args) { new Test1(); } } OutPut 788) 789) 790) 791) 792) 793) 794) 795) 796) 797) 798) 799) 800) 801) 802) 803) 804) OutPut 806) 807) 808) 809) 810)
D:\bin>javac Demo1.java D:\bin>java Demo1 In Test1 static block class Test1 { static { System.out.println("In Test1 first static block"); } static { System.out.println("In Test1 second static block"); } public static void main(String[] args) { new Test1(); } } D:\bin>javac Demo1.java D:\bin>java Demo1 In Test1 first static block In Test1 second static block
811) Note – If there are multiple static blocks than it will execute in the sequence has they present 812)
Core Java 813) 814)
Static Block
816) Gets executed before running the main method. Or it get executed at the time of class get loaded 818) These blocks are used to initialize the static members (static variables) of class 820) These block get executed only once for entire program execution 822) Inside static block static members can be accessed directly where as non static members should be accessed by using the reference of the object 823) 824) class StaticBlock 825) { 826) int a=23; 827) static int b=15; 828) 829) static { 830) System.out.println("Adding two number."); 831) 832) int sum=0; 833) sum = a + b; //Error because a is non-static. b can be accessed because b is static 834) } 835) 836) } 837) 853) Static block is called has static initialization block (SIB) 855) 856)
815)
Non-Static Block
817) Gets executed at the time of Object creation. Or it get executed only after creating a object of class 819) These blocks are used to initialize the non-static members (instance variables) of class 821) These block get executed when ever the new object is created 838) Inside the non-static block, both static and non-static members can be accessed directly 839) 840) 841) class InstanceBlock 842) { 843) int a=23; 844) static int b=15; 845) 846) { 847) System.out.println("Addition of two numbers......"); 848) int sum=0; 849) sum = a + b; // no error because its non-static block 850) } 851) 852) }
854) Non-static block is called has instance initialization block (IIB)
Difference between constructor and method
857) Constructor 859) Name of constructor should be same has the class name 861) Constructor cannot be inherited 863) Constructor cant return anything 865) By default the compiler will have a default constructor 867) Constructor is used to initialize the instance variables of class
858) Method 860) Name of method can be anything other than a class name 862) Method can be inherited 864) Method can return a value 866) There is nothing called has default meth 868)
Method is used to tell the behavior of cl
Core Java 869) 870) 871)
Core Java
872) Method Overriding 873) Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class. 874) 875) A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass to modify the methods defined in the superclass. This is referred to as method overriding. The following example demonstrates method overriding. 876) 877) class Father 878) { 879) String name; 880) double height; 881) int age; 882) 883) void factory() 884) { 885) System.out.println("Parent factory()"); 886) } 887) void home() 888) { 889) System.out.println("some home()"); 890) } 891) } 892) 893) class Son extends Father 894) { 895) 896) void factory() //Son modifying Father factory() 897) { 898) System.out.println("modified Parent factory() by Son“); 899) } 900) void home() //Son modifying Father factory() 901) 902) { 903) System.out.println("modified Parent home() by Son"); 904) } 905) } 906) public class Test { 907) public static void main(String[] args) { 908) Father f = new Son(); 909) 910) f.factory(); //hear the Son's factory() is called, because Parent factory() is overridden by Son 911) 912) f.home(); //hear the Son's home() is called, because Parent home() is overridden by Son 913) } 914) } 915) 916)
Core Java 917)
Core Java 918)
Rules for method overriding:
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overriding method in the sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
Constructors cannot be overridden.
919) Type Casting in JAVA 920) Java supports two types of castings – primitive data type casting and reference type casting. Reference type casting is nothing but assigning one Java object to another object. It comes with very strict rules and is explained clearly in Object Casting(next topic). Now let us go for data type casting. 921)
a) data type casting
922)
Java data type casting comes with 3 flavors.
1. Implicit casting 2. Explicit casting 3. Boolean casting.
Core Java 923)
1. Implicit casting (widening conversion)
924) A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is done implicitly by the JVM. The lower size is widened to higher size. This is also named as automatic type conversion. 925) class Vikas 926) { 927) public static void main(String[] args) { 928) 929) int a = 10; 930) double d = a; 931) System.out.println(d); //prints 10.0 932) 933) } 934) } 935)
2. Explicit casting (narrowing conversion)
936) A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size. This is not done implicitly by the JVM and requires explicit casting; a casting operation to be performed by the programmer. The higher size is narrowed to lower size. 937) 938) 939) 940) 941) 942) 943) 944) 945) 946) 947)
class Vikas { public static void main(String[] args) {
948)
}
949)
3. Boolean casting
double d = 10.89; int c = d ; //Error double d = 10.89; int c = d ; //Error int a = (int)d; //explicit casting }
950) A boolean value cannot be assigned to any other data type. Except boolean, all the remaining 7 data types can be assigned to one another either implicitly or explicitly; but boolean cannot. We say, boolean is incompatible for conversion. 951)
NOTE :
952)
byte –> short –> int –> long –> float –> double
953) In the above statement, left to right can be assigned implicitly and right to left requires explicit casting. That is, byte can be assigned to short implicitly but short to byte requires explicit casting. 954)
b) Reference type casting
Subclass object can be assigned to a super class object and this casting is done implicitly. This is known as upcasting (upwards in the hierarchy from subclass to super class)
Core Java
961) 962) 963) 964) 965) 966) 967) 968) 969) 970) 971) 972) 973) 974) 975) 976) 977) 978) 979) 980) 981) 982) 983) 984) 985) 986) 987) 988) 989) 990) 992)
955) Eg : Father f = new Son();//implicit casting 956) Java does not permit to assign a super class object to a subclass object (implicitly) and still to do so, we need explicit casting. This is known as down casting (super class to subclass). Down casting requires explicit conversion. In down casting , first you need to do the upcasting after upcasting than only u can perform the down casting. Or else its a classCastException 957) Eg : Father f = new Son(); //upcasting 958) Son s = (Son) f; //down casting 959) 960) Son s = (Son) new Father(); //compiles but at runtime give exception class Father { void factory() { System.out.println("Parent factory()"); } void home() { System.out.println("some home()"); } } class Son extends Father { void factory() { System.out.println("modified Parent factory() by Son"); } void home() { System.out.println("modified Parent home() by Son"); } void car() { System.out.println("Son alone has car()"); } } 991) implicit casting (implicit UPCASTING)
993) public class Test { 994) public static void main(String[] args) 995) { 996) Father f = new Son();//implicit casting 997) f.factory(); 998) f.home(); 999) f.car(); //Error cant accesses Son class methods using parent reference 1000) } 1001) } 1002)
explicit casting (explicit DOWNCASTING)
Core Java 1003) public class Test { 1004) public static void main(String[] args) { 1005) Father f = new Son();// implicit casting 1006) Son s = (Son)f; 1007) s.factory(); 1008) s.home(); 1009) s.car(); //no error because the explicit casting is done 1010) } 1011) } 1012) So by explicit casting we can accesses the child class members using the parent class reference 1013) 1014)
Core Java
1015) Abstract class 1016) An abstract class is a class that is declared with the abstract key word, it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be sub classed. Cant create the object of abstract class 1017) public abstract class Game 1018) { 1019) //abstract class without any methods 1020) } 1021) 1022) public abstract class Cade 1023) { 1024) 1025) abstract void draw(); 1026) 1027) //abstract class with abstract methods 1028) } 1029) 1030) abstract class Plan 1031) { 1032) void costEstimation() 1033) { 1034) //some code to tell about cost to build 1035) } 1036) abstract void baseMent(); 1037) abstract void build(); 1038) 1039) } //abstract class with concreate and abstract methods 1040) 1041) Whenever you inherit the abstract class you need to override the abstract methods of the abstract(PARENT) class in the inherited (CHILD) class. OR else you should declare the child class also has abstract class. See the example below 1042) 1043) 1044) 1045) 1046) 1047) 1048) 1049) 1050) 1051) 1052) 1053) 1054) 1055) 1056) 1057) 1058) 1059)
Example : class Volvo { void body() { //code } void ac(); void music(); void seats(); } abstract class ElectricWork extends Volvo { void ac() { //code }
Core Java 1060) void music() 1061) { 1062) //code 1063) } 1064) } 1065) class KSRTC extends ElectricWork 1066) { 1067) void seats() 1068) { 1069) //code 1070) } 1071) } 1072) Hear ElectricWork class is also abstract because all the abstract methods of Volvo class has not been overridden in this class, i.e seats() method is not overridden. 1073) KSRTC class has overridden all the parents class abstract methods so it need not to be abstract class 1074) Important Points about Abstract class abstract keyword is used to make a class abstract.
Abstract class can’t be instantiated.
We can use abstract keyword to create an abstract method, an abstract method doesn’t have body.
If a class have abstract methods, then the class also needs to be made abstract using abstract keyword, else it will not compile.
Its not necessary to have abstract classes to have abstract method.
If abstract class doesn’t have any method implementation, its better to use interface because java doesn’t support multiple class inheritance.
The subclass of abstract class must implement all the abstract methods unless the subclass is also an abstract class.
Abstract classes can implement interfaces without even providing the implementation of interface methods.
Abstract classes are used to provide common method implementation to all the subclasses or to provide default implementation.
Abstract class can have a constructor but it can be called from the child class using supper statement
We can run abstract class like any other class if it has main() method.
In interview give some good examples like bank or google example (refer class notes)
1075) Example1: abstract class MediaPlayer
Core Java 1076) 1077) 1078) 1079) 1080) 1081) 1082) 1083) 1084) 1085) 1086) 1087) 1088) 1089) 1090) 1091) 1092) 1093) 1094) 1095) 1096) 1097) 1098) 1099) 1100) 1101) 1102) 1103) 1104) 1105) 1106) 1107)
{ void playSong(String songName) { System.out.println(songName+" is playing in the player"); } abstract void pauseControle(); abstract void screenControler(); } class Windows extends MediaPlayer { void pauseControle() { System.out.println("Press P to pause the song"); } void screenControler() { System.out.println("Do changes using menu button"); } } class VLC extends MediaPlayer { void pauseControle() { System.out.println("Press space-bar to pause the song"); } void screenControler() { System.out.println("Press A to change the screen size"); } }
1108)
1109) Interface Interface in java is one of the way to achieve 100% abstraction in Java . Interface in java is declared using keyword interface. It is also just like normal class. For interface also the .class file is going to be generated. All methods inside interface are public by default All variables declared inside interface is implicitly public final variable or constants. 1110) 1111)
interface Office { 1112) int employee;//Error because only final variables so they need to be initialised has donoted in below example. No other types are allowed inside interface 1113) } 1114) 1115)
interface Office {
Core Java 1116)
int employee=100; 1117)
}
All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword Cant create the Object of interface In Java its legal for an interface to extend multiple interface. for example following code will run without any compilation error 1118) 1119) 1120) 1121) 1122) 1123) 1124) 1125) 1126) 1127) 1128) 1129) 1130) 1131) 1132)
package com.vikas.jspiders; interface Animal { public void eat(); public void walk(); } interface Human { public void talk(); public void work(); } interface Livingbeing extends Animal,Human // extend multiple interface { public void enjoyWithLover(); }
1133) Whenever we implement interface we need to provide implementation to all the abstract methods of it, or else we need to make the inherited class also has abstract. 1134) interface Office 1135) { 1136) void work(); 1137) public void enjoy(); 1138) } 1139) abstract class Manager implements Office 1140) { 1141) //implementation is not give for work() and enjoy() so class should be abstract 1142) } 1143) 1144) Example:1145) interface Animal 1146) { 1147) public void eat(); 1148) public void walk(); 1149) } 1150) interface Human 1151) { 1152) public void talk(); 1153) public void work(); 1154) } 1155) interface Livingbeing extends Animal,Human 1156) { 1157) public void enjoyWithLover(); 1158) } 1159) public class Test implements Livingbeing{ 1160)
Core Java 1161) public void eat() 1162) { 1163) // TODO Auto-generated method stub 1164) } 1165) public void walk() 1166) { 1167) // TODO Auto-generated method stub 1168) } 1169) public void talk() 1170) { 1171) // TODO Auto-generated method stub 1172) } 1173) public void work() 1174) { 1175) // TODO Auto-generated method stub 1176) } 1177) public void enjoyWithLover() 1178) { 1179) // TODO Auto-generated method stub 1180) } 1181) 1182) } 1183) 1184) The Interface reference can be give to its child class object. It behave same has the inheritance. Using the interface reference we cant accesses the child class members. But we can accesses the overrided methods. 1185) 1186) Example: 1187) 1188) interface Animal 1189) { 1190) public void eat(); 1191) public void walk(); 1192) } 1193) 1194) class Cow implements Animal 1195) { 1196) 1197) public void eat() 1198) { 1199) System.out.println("Cow eat hullu"); 1200) } 1201) 1202) public void walk() 1203) { 1204) System.out.println("Cow walk in four legs"); 1205) } 1206) public void giveMilk() 1207) { 1208) System.out.println("Cow give white milk"); 1209) } 1210) 1211) } 1212) class Test1 1213) { 1214) public static void main(String[] args) {
Core Java 1215) 1216) 1217) 1218) 1219) members 1220) } 1221) } 1222) 1223) 1226) Multiple Inheritance 1229) Concrete methods (Default Behavior)
1232) Access Modifiers
1235) 1236) Methods and variables
Animal a = new Cow(); a.eat(); a.walk(); a.giveMilk();//Error because parent reference cant accesses child
1224) Abstract 1227) A class can inherit only one Abstract Class 1230) In abstract class you can provide default behavior of a method, so that even if child class does not provide its own behavior, you do have a default behavior to work with 1233) You can provide access modifiers to methods in abstract classes (static , final, etc) 1237) The methods or variables can be declared with any accesses specifiers and modifiers. (Note : but abstract methods should not be static , final, private) 1238)
1225) Interface 1228) A class can implement multiple Interfaces 1231) You cannot provide a default behavior in interfaces. Interfaces only allow you to provide signature of the method
1234) You cannot provide access modifiers methods in Interfaces. 1239) All methods are public by default, all the variables are static final by default. 1240)
1241)
1242) Abstraction 1243) abstraction in Java is used to hide certain details and only show the essential features of the object. 1244) Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery. 1245) Abstraction lets you focus on what the object does instead of how it does it. 1246)We are going to achieve abstraction using 1247) Abstract class 1248) Interface 1249)
1250) Encapsulation
Core Java 1251) 1252) Encapsulation is the packing of data and functions into a single component. Encapsulation is the ability to package data, related behaviour in an object bundle and control/restrict access to them (both data and function) from other objects. It is all about packaging related stuff together and hide them from external elements. 1253) Encapsulation can be achieved by declaring fields in a class as private, while providing access to these fields via public, typically, getter and setter methods. Or else we can tell that the encapsulation can be achieved by java beans. 1254) 1255) 1256) 1257) 1258) 1259) 1260) 1261) 1262) 1263) 1264) 1265) 1266) 1267) 1268) 1269) 1270) 1271) 1272) 1273) 1274) 1275) 1276) 1277) 1278) 1279) 1280) 1281) 1282) 1283) 1284) 1285) 1286) 1287) 1288) 1289) 1290) 1291) 1292) 1293) 1294) 1295) 1296) 1297) 1298) 1299)
package com.vikas.jspiders; import java.util.Scanner; class Register { private String name,email,password; private int age; private long phone; private double hight; private char gender; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public long getPhone() { return phone; } public void setPhone(long phone) { this.phone = phone; } public double getHight() { return hight; } public void setHight(double hight) { this.hight = hight;
Core Java 1300) } 1301) public char getGender() { 1302) return gender; 1303) } 1304) public void setGender(char gender) { 1305) this.gender = gender; 1306) } 1307) 1308) } 1309) class RegisterDetails 1310) { 1311) void insertDetails(Register r) 1312) { 1313) System.out.println("Name is "+r.getName()); 1314) System.out.println("Email is "+r.getEmail()); 1315) System.out.println("Password is "+r.getPassword()); 1316) System.out.println("Age is "+r.getAge()); 1317) System.out.println("Gender is "+r.getGender()); 1318) System.out.println("Phone number "+r.getPhone()); 1319) System.out.println("Height is "+r.getHight()); 1320) 1321) } 1322) } 1323) public class Demo { 1324) public static void main(String[] args) { 1325) 1326) 1327) Scanner scan = new Scanner(System.in); 1328) System.out.println("Enter the name"); 1329) String name = scan.next(); 1330) System.out.println("Enter the Email"); 1331) String email = scan.next(); 1332) System.out.println("Enter the password"); 1333) String password = scan.next(); 1334) System.out.println("Enter the age"); 1335) int age=scan.nextInt(); 1336) System.out.println("Enter phone number"); 1337) long l = scan.nextLong(); 1338) System.out.println("Enter height"); 1339) double height = scan.nextDouble(); 1340) System.out.println("Enter gender"); 1341) char gender =(char) scan.next().charAt(0); 1342) 1343) Register r = new Register(); 1344) r.setName(name); 1345) r.setEmail(email); 1346) r.setPassword(password); 1347) r.setHight(hight); 1348) r.setAge(age); 1349) r.setGender(gender); 1350) 1351) RegisterDetails rd = new RegisterDetails(); 1352) rd.insertDetails(r);// hear the bean object is sent to the insertDetails method in RegisterDetails class 1353) } 1354)
Core Java 1355) } 1356) 1357)
Output
1358) 1359) 1360) 1361) 1362) 1363) 1364) 1365) 1366) 1367) 1368) 1369) 1370) 1371) 1372) 1373) 1374) 1375) 1376) 1377) 1378) 1379) 1380) 1381)
Enter the name vikas Enter the Email
[email protected] Enter the password 12345 Enter the age 25 Enter phone number 8147214063 Enter height 5.5 Enter gender M Out put after taking input Name is vikas Email is
[email protected] Password is 12345 Age is 25 Gender is M Phone number 8147214063 Height is 5.5
1382)
1383) Polymorphism 1384) 1385) Polymorphism is the ability by which, we can create functions or reference variables which behaves differently in different programmatic context. Polymorphism is a Greek word which means many(poly) forms(morphism). 1386) Polymorphism is tightly coupled to inheritance and is one of the most powerful advantages to object-oriented technologies. 1387)
Polymorphism is essentially considered into two versions.
1. Compile time polymorphism (static binding or method overloading) 2. Runtime polymorphism (dynamic binding or method overriding) 1388) Note : see class notes for overload and overriding examples
1389)
Static binding
1391) When type of the object is determined at compiled time(by the compiler), it is known as static binding
1390)
Dynamic binding
1392) When type of the object is determined at run-time, it is known as dynamic binding
Core Java
1393) If there is any private, final or static method in a class, there is static binding
1394) Other methods than private , final , static
1395) Static binding uses Type(Class in Java) information for binding
1396) Dynamic binding uses Object to resolve binding.
1397) Overloaded methods are bonded using static binding
1398) Overridden methods are bonded using dynamic binding at runtime.
1399)
Compile time polymorphism 1400)
Runtime polymorphism
1401) 1402) 1403) What Is a Package? 1404) Packages are nothing but folder structure. It groups different class and files according to their relations which performs corresponding relation. (Eg : How you keep the photos separately in the folders, and also sometimes u group different photos into different folders) 1405) Steps to create package – Create New Java Project Select src folder and right click on it and select the package option Than give the package name has you like but it is good practice to start the package name with com (eg : com.vikas.jspider) com means commercial Or you can right click on src and select the new and than u can also select folder name and type the name and create the package 1406) 1407) Note – Package name should be the 1st line of the code 1408) 1409) What is import? 1410) We use import statement to indicate for our JVM to import the particular class from the package 1411) Note – Import must be immediate line after the package and before the class We cannot import different class which has the same name from multiple packages It imports class which r in same package but it does not import the class which are present in sub packages. So we need to import them The java.lang package is imported by the compiler, and we need not to do it explicitly. The java.lang package is the default package 1412) 1413)
Structure of code
Core Java 1414) Package Name 1415) 1416) Import statements 1417) 1418) class 1419)
{
1420) /code 1421)
/ }
1422) 1423)
1424) Accesses specifiers
Public Protected Default Private The accesses specifiers will define the scope of every member In java accessibility of any member can be controlled by using accesses modifiers. In picture the accessibility can be given has
1425) PUBLIC is the high visible access specifier in java which can be accessed every were PRIVATE is the highly restricted access specifier in java that it can be accessed form only inside the class. Such that the members which are declared has private cannot be accessed from outside the class DEFAULT the scope of default members in only inside the package. They can be accessed within package but not from outside the package. If we don’t specify any access specifier than the member would be taken has default access specifier
Core Java PROTECTED the protected members can be accessed within the package, but they can be accessed outside the package also only in the case of inheritance 1426)
1427) Access modifiers 1428) We know access specifiers specify the access and access modifiers modify the access of variables, methods and classes. In general, an access modifier works between the classes of the same application or within the classes of same package. 1429) Six modifiers exist that can be used with methods. 1430) 1431) final Subclass cannot override 1432) abstract No method body exists 1433) native Java method takes the help of underlying OS 1434) static Object is not necessary to call 1435) synchronized Used to lock the source and renders a thread-safe operation 1436) strictfp Guarantees the same precision for floating-point values in the class irrespective of the OS on which the program is executed 1437) 1438) Four modifiers and four specifiers exist that can be applied to variables 1439) 1440) static Also known as "class variable". No object is necessary to call 1441) final cannot be reassigned 1442) transient Not serialized 1443) volatile Value is more liable to change 1444) 1445) 1446) Three modifiers exist that can be applied to classes. Modifier comes just before the class name 1447) 1448) abstract Objects cannot be created 1449) final cannot be inherited 1450) strictfp Guarantees the same precision for floating-point values in the class irrespective of the OS on which the program is executed 1451) 1452) Points to note in method overriding with respect to access specifiers 1453)
If super class method is public, while overriding it in child class, it should be public, Since it is the weakest access specifier or least restrictive access specifier If super class method is protected, while overriding it in child class, it can be public or protected but not anything else If superclass method is default, then while overriding it in child class, it can be public, protected or no access, but cannot be private. If superclass method is private, then while overriding it in child class, it can be anything. Since private method cannot be overrided. Singleton
1454) One instance allowed for a class. In the séance we can create only one object of that class and we cant create multiple object of that class. 1455)
public class SingletonObject {
Core Java 1456)
private SingletonObject()
1457)
{
1458)
}
1459)
private static SingletonObject singleObject=new SingletonObject();
1460)
public static SingletonObject giveObject()
1461)
{
1462)
return singleObject;
1463)
}
1464)
}
1465)
Program to get the object of this SingletonObject class
1466)
public class TestForSingle {
1467)
public static void main(String[] args) {
1468)
SingletonObject obj1=SingletonObject.giveObject();
1469)
System.out.println(obj1);
1470)
SingletonObject obj2=SingletonObject.giveObject();
1471)
System.out.println(obj2);
1472) } 1473)
}
1474) OutPut of the above program is it will print the reference of the Objects, has it is singleton only one object is created so both have same reference 1475) com.vikas.SingletonObject@19821f 1476) com.vikas.SingletonObject@19821f 1477)
Core Java
1478) Object Class 1479) Object class is the super class of all the classes in java. The Object class reference can be given to any child object or any class object. Every class in the Java system is a descendent (direct or indirect) of the Object class 1480) The object class methods are public int hashCode() public boolean equals(Object obj) public String toString() protected Object clone() protected void finalise() public final Class getClass() public final void notify() public final void notifyAll() public final void wait(long time) public final void wait(long time, int nanoSec) public final void wait() 1481) 1482) hashCode() If you only override hash-code method nothing will happen. It will return the same hashcode for all the objects of that class. In the below example all the objects of cow class will have the same hash code 123. 1483) If you don’t override hash-code method nothing will happen Because it always return new hash-code for each object as an Object class. Overriding only hash code method will not have much effect, so whenever u over ride hash code method better to override the equals(Object) method also.
1484) 1485) 1486) 1487) 1488) 1489) 1490) 1491) 1492) 1493) 1494) 1495) 1496) 1497) 1498) 1499) 1500) 1501) 1502) 1503) 1504) 1505) 1506) 1507)
package com.vicky; public class Cow { String name; void giveMilk() { System.out.println("Cow give milk"); } public int hashCode() //over riding hash code method { return 123; } } package com.vicky; public class CheckHashCode { public static void main(String[] args) { Cow c = new Cow(); c.name="getha"; System.out.println(c);
Core Java 1508) Cow c1 = new Cow(); 1509) c1.name="getha"; 1510) System.out.println(c1); 1511) 1512) System.out.println("c.equals(c1) is "+c.equals(c1)); 1513) } 1514) } 1515) 1516) OutPut 1517) com.vicky.Cow@7b (Note – 7b is a hexa decimal value of 123) 1518) com.vicky.Cow@7b 1519) 1520) c.equals(c1) is false 1521) 1522) We generally override hash code method in HashSet , HashMap. Hear even though the both the objects hash code is same and also the content is same, c.equals(c1) is false. So over riding only hash code method will not give us the proper result we need, so whenever we over ride the hash code method we should also over ride the equals(Object) method also 1523) 1524) equals(Object obj) This method is used to tell whether the objects are equal are not, it always checks for the content of the object 1525) 1526) package com.vicky; 1527) public class CheckHashCode 1528) { 1529) public static void main(String[] args) 1530) { 1531) Cow c = new Cow(); 1532) c.name="getha"; 1533) c.age=24; 1534) System.out.println(c); 1535) 1536) Cow c1 = new Cow(); 1537) c1.name="getha"; 1538) c1.age=24; 1539) System.out.println(c1); 1540) 1541) System.out.println("c.equals(c1) is "+c.equals(c1)); 1542) 1543) } 1544) } 1545) 1546) package com.vicky; 1547) public class Cow 1548) { 1549) String name; 1550) int age; 1551) void giveMilk() 1552) { 1553) System.out.println("Cow give milk"); 1554) } 1555) public int hashCode() 1556) { 1557) int a = this.name.hashCode();
Core Java 1558) return a; 1559) } 1560) 1561) public boolean equals(Object obj) { 1562) if(obj instanceof Cow) 1563) { 1564) Cow c = (Cow) obj; 1565) if(this.name.hashCode()==c.name.hashCode()) 1566) { 1567) if(this.age==c.age) 1568) { 1569) return true; 1570) } 1571) else 1572) { 1573) return false; 1574) } 1575) 1576) return true; 1577) } 1578) else 1579) return false; 1580) } 1581) else 1582) return false; 1583) } 1584) } 1585) OutPut 1586) com.vicky.Cow@5db1ecf 1587) com.vicky.Cow@5db1ecf 1588) 1589) c.equals(c1) is true 1590) equals method always check for the content of the object, so I have overridden my class equals method which also check the content of my class objects. 1591) 1592) toString() 1593) The toString() method in the Object class is used to display some information regarding any object. If any code needs some information of an object of a class, then it can get it by using this method. The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method. 1594) 1595) package com.vicky; 1596) public class Cow 1597) { 1598) String name; 1599) void giveMilk() 1600) { 1601) System.out.println("Cow give milk"); 1602) } 1603) 1604) public String toString() { 1605) return "this is a Cow class"; 1606) } 1607) } 1608) package com.vicky;
Core Java 1609) 1610) 1611) 1612) 1613) 1614) 1615) 1616) 1617) 1618) 1619) 1620) 1621) 1622) 1623) 1624) 1625) 1626) 1627)
public class CheckHashCode { public static void main(String[] args) { Cow c = new Cow(); c.name="getha"; System.out.println(c); Cow c1 = new Cow(); c1.name="getha"; System.out.println(c1); } } Output this is a Cow class this is a Cow class clone()
1628) The object cloning is a way to create exact copy of an object. In cloning the content of that object is also cloned(copied) into the new object. But both the objects are different from one another, change in one object after cloning will not affect the content of another object. 1629) The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. 1630) 1631) 1632) 1633) 1634) 1635) 1636) 1637) 1638) 1639) 1640) 1641) 1642) 1643) 1644) 1645) 1646) 1647) 1648) 1649) 1650) 1651) 1652) 1653) 1654)
public class Cow implements Cloneable { String name; void giveMilk() { System.out.println("Cow give milk"); } protected Object clone() throws CloneNotSupportedException { return super.clone(); } } public class CheckHashCode { public static void main(String[] args) throws CloneNotSupportedException { Cow c = new Cow(); c.name="getha"; System.out.println(c); Cow newObj = (Cow) c.clone(); } }
Core Java 1655) 1656) Scanning input in java 1657) In java we can scan the input in different ways BufferedReader and InputStreamReader classes DataInputStream class Console class Scanner class 1658) 1659) An InputStreamReader is a bridge from byte streams to character streams, It reads bytes and decodes them into characters. The BufferedReader class provides buffering to your Reader's. Buffering can speed up IO quite a bit. Rather than read one character at a time from the network or disk, you read a larger block at a time. This is typically much faster, especially for disk access and larger data amounts. 1660) The main difference between BufferedReader and BufferedInputStream is that Reader's work on characters (text), wheres InputStream's works on raw bytes. 1661) 1662) voi 1664) voi 1666) boo
1663) close( ) Closes the stream and releases any system resources associated with it. 1665)
mark(int readAheadLimit) Marks the present position in the stream.
1667) markSupported( ) Tells whether this stream supports the mark() operation, which it does.
1668) int
1669)
read( ) Reads a single character.
1670) int
1671) array.
read(char[ ] cbuf, int off, int len) Reads characters into a portion of an
1672) Stri
1673)
readLine( ) Reads a line of text.
1674) boo
1675)
ready( ) Tells whether this stream is ready to be read.
1676) voi
1677)
reset ( ) Resets the stream to the most recent mark.
1678) lon
1679)
skip(long n) Skips characters.
1680) 1681) 1682)
package com.vikas.jspiders; import java.io.BufferedReader;
Core Java 1683) import java.io.IOException; 1684) import java.io.InputStreamReader; 1685) public class BufferedReaderClass { 1686) public static void main(String[] args) throws IOException 1687) { 1688) BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 1689) System.out.println("Enter the carector"); 1690) char c = (char)br.read(); // reads a single charector 1691) System.out.println("Enter the String"); 1692) String name = br.readLine(); // reads the string set of charectors 1693) System.out.println("Charector is "+c); 1694) System.out.println("String is "+name); 1695) } 1696) } 1697) 1698) A DataInputStream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream. DataInputStream is not necessarily safe for multithreaded access. Thread safety is optional and is the responsibility of users of methods in this class. Refer File Handling for more example on this class 1699) 1700) package com.vikas.jspiders; 1701) import java.io.DataInputStream; 1702) import java.io.IOException; 1703) 1704) public class DataInputStreamClass { 1705) public static void main(String[] args) throws IOException 1706) { 1707) DataInputStream d = new DataInputStream(System.in); 1708) System.out.println("Enter string"); 1709) String name = d.readLine(); 1710) System.out.println(name); 1711) } 1712)
}
1713) 1714) Console class Actually this is a class in Java that used to input and output to the console window. There are many methods which are used to read the input and methods to print the output also. But this class does not work with your ID such has eclipse so please try this example with your command prompt. 1715) 1716) package com.vikas.jspiders; 1717) import java.io.Console; 1718) import java.io.IOException; 1719) 1720) public class ScannerClass { 1721) public static void main(String[] args) throws IOException 1722) { 1723) Console c = System.console(); 1724) String s = c.readLine();
Core Java 1725) 1726) 1727) 1728) }
char sp[] = c.readPassword(); System.out.println(sp[1]); }
1729) 1730) Scanner is a class in java. Which is present in java.util package. Scanner is used to scan the input for the program. Scanner will help to scan the input from the keyboard and also we can read the content of the file has a input for the program. 1731) 1732) Scanner scanFromKey = new Scanner(System.in); 1733) 1734) Scanner scanFromFile = new Scanner(new FileReader("vikas.txt")); 1735) 1736) Methods of scanner class 1737) 1738) Method 1739) Description 1740) byte nextByte() 1741) To scan the byte 1742) short nextShort() 1743) To scan the short 1744) int nextInt( ) 1745) To scan the int, there are also some methods like nextBigInteger( ) 1746) double nextDouble( ) 1747) To scan double 1748) float nextFloat( ) 1749) To scan the float 1750) String next( ) 1751) To scan the string until the space in encountered 1752) String nextLine( ) 1753) To scan the entire line until the new line carector is encountered 1754) 1755) There are few more methods present in the scanner class, they are just used to find the next type of element stored in the input. 1756) 1757)
Method
1758)
Returns
1759) boolean hasNextLine()
1760) Returns true if the scanner has another line in its input; false otherwise.
1761) boolean hasNextInt()
1762) Returns true if the next token in the scanner can be interpreted as an int value.
1763) boolean hasNextFloat()
1764) Returns true if the next toke in the scanner can be interpreted as a float value.
1765) 1766) 1767) 1768) 1769) 1770) 1771)
package com.vikas.jspiders; import java.util.Scanner; public class ScannerClass { public static void main(String[] args)
Core Java 1772) 1773) 1774) 1775) 1776) 1777) 1778) 1779) 1780) 1781) 1782) 1783) 1784) 1785) 1786) 1787) 1788) 1789) 1790) 1791) 1792) 1793) 1794)
{ double number; Scanner in = new Scanner(System.in); System.out.println("Enter your gross income: "); if (in.hasNextInt()) { number = (double)in.nextInt(); System.out.println("You entered " + number); } else if (in.hasNextFloat()) { number = (double)in.nextFloat(); System.out.println("You entered " + number); } else if (in.hasNextDouble()) { number = in.nextDouble(); System.out.println("You entered " + number); } else System.out.println("Token not an integer or a real value."); } }
Core Java
1795) String class 1796) Java String is a immutable object. For an immutable object you cannot modify any of its attribute’s values. Once you have created a java String object it cannot be modified to some other object or a different String. String is one of the widely used java classes 1797)
Strings are not null terminated in Java. Strings are immutable and final in Java Strings are maintained in String Pool Use equals methods for comparing String in Java Use indexOf() and lastIndexOf() or matches(String regex) method to search inside String Use SubString to get part of String in Java "+" is overloaded for String concatenation Use trim() to remove white spaces from String Use split() for splitting String using Regular expression
1798) Difference between String , StringBuffer and StringBuilder 1799) The most important difference between String and StringBuffer , StringBuilder in java is that String objects are immutable ( can’t change the content of String Object) 1800) StringBuffer and StringBuilder objects are mutable ( can change the content of StringBuffer and StringBuilder objects). StringBuilder and StringBuffer are almost the same. 1801) The difference is that StringBuffer is synchronized and StringBuilder is not. Although, StringBuilder is faster than StringBuffer, the difference in performance is very little. StringBuilder is a SUN's replacement of StringBuffer. It just avoids synchronization from all the public methods. Rather than that, their functionality is the same. 1802) 1803) We can create the objects of String , StringBuilder and StringBuffer has shown below. There are few methods in each class refer them. 1804) String 1805) String name = “vikas”; 1806) String place = new String(“banavara”); 1807) 1808) String buffer 1809) StringBuffer sbf = new StringBuffer( ); 1810) sbf.append(“Hassan”); 1811) StringBuffer sbf = new StringBuffer(10); 1812) sbf.append(“Banglore”); 1813) StringBuffer sbf = new StringBuffer(“Mysore”); 1814) 1815) String builder 1816) StringBuilder sbr = new StringBuilder ( ); 1817) sbr.append(“Kannada”); 1818) StringBuilder sbr = new StringBuilder (10); 1819) sbr.append(“Kaaveri”); 1820) StringBuilder sbr = new StringBuilder (“Mysore”); 1821) 1822)
Core Java
1823) Assertion 1824) Asseertion is a statement, it is used to detect the program errors. We can tell that assertion is used to rais the error, if anything goes wrong while running the program. 1825) Syntax 1 : assert expression; 1826) If the expression is not true than the AssertionError is going to be generated 1827) 1828) import java.util.Scanner; 1829) public class Program { 1830) public static void main(String[] args) { 1831) Scanner scan = new Scanner(System.in); 1832) System.out.println("Enter the age of voter"); 1833) int voter = scan.nextInt(); 1834) assert (voter>=18); 1835) System.out.println("Thank you for voting"); 1836) } 1837) } Note : Run has java -ea Program (-ea means enable assertion) 1838) Output 1839) Enter the age of voter 1840) 21 1841) Thank you for voting 1842) Output 1843) Enter the age of voter 1844) 15 1845) Exception in thread "main" java.lang.AssertionError 1846) at com.vikas.jspiders.AssertionProgram.main(AssertionProgram.java:9) 1847) 1848) Syntax 2 : assert expression : message; 1849) If the expression is not true than the message is going to be printed along with the line number and class name; 1850) import java.util.Scanner; 1851) public class AssertionProgram { 1852) public static void main(String[] args) { 1853) Scanner scan = new Scanner(System.in); 1854) System.out.println("Enter the age of GIRL and BOY "); 1855) int girl = scan.nextInt(); 1856) int boy = scan.nextInt(); 1857) 1858) assert (girl>=18) : "girl is too young"; 1859) assert (boy>=21) : "Boy is too young"; 1860) 1861) System.out.println("You can mari each other wish u good luck"); 1862) } 1863) } Note : Run has java -ea Program (-ea means enable assertion) 1864) Output 1865) Enter the age of GIRL and BOY 1866) 15 1867) 23 1868) Exception in thread "main" java.lang.AssertionError: girl is too young 1869) at com.vikas.jspiders.AssertionProgram.main(AssertionProgram.java:13) 1870) 1871)
Core Java
1872) Enumeration 1873) The Java programming language contains the enum keyword, which represents a special data type that enables for a variable to belong to a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. 1874) The values defined inside an enum are constants. Also, these values are implicitly static and final and cannot be changed, after their declaration. If an enum is a member of a class, then it is implicitly defined as static. Finally, you should use an enum, when you need to define and represent a fixed set of constants. 1875) class Test 1876) { 1877) enum E 1878) { 1879) a, b, c, d; 1880) } 1881) public static void main(String[] args) 1882) { 1883) E e1 = E.b; 1884) System.out.println(e1); 1885) E e2 = E.d; 1886) System.out.println(e2); 1887) System.out.println(e1.ordinal());//ordinal() is used to get the position of that enum 1888) System.out.println(e2.ordinal()); 1889) System.out.println(E.valueOf("a").ordinal()); 1890) } 1891) } 1892) Output 1893) b 1894) d 1895) 1 1896) 3 1897) 0 1898) Enums in Java are considered to be reference types, like class or Interface and thus, a programmer can define constructor, methods and variables, inside an enum 1899) An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Apex provides built-in enums, such as LoggingLevel, and you can define your own enum. 1900) All Apex enums, whether user-defined enums or built-in enums, have the following common method that takes no arguments. 1901) values 1902) This method returns the values of the Enum as a list of the same Enum type. Each Enum value has the following methods that take no arguments. 1903) name 1904) Returns the name of the Enum item as a String. 1905) ordinal 1906) Returns the position of the item, as an Integer, in the list of Enum values starting with zero. 1907) 1908)
Core Java 1909) 1910) 1911) 1912) 1913) 1914) 1915) 1916) 1917) 1918) 1919) 1920) 1921) 1922) 1923) 1924) 1925) 1926) 1927) 1928) 1929) 1930) 1931) 1932) 1933) 1934) 1935) 1936) 1937) 1938) 1939) 1940) 1941) 1942)
Example2: class Test { enum Month { JAN(31), FEB(28), MAR(31);
1943)
Output
1944) 1945) 1946) 1947) 1948) 1949) 1950)
FEB 28 28 -------JAN 31 31
int days; Month(int days) { this.days = days; } int getDays() { return days; } } public static void main(String[] args) { Month m1 = Month.FEB; System.out.println(m1); System.out.println(m1.getDays()); System.out.println(m1.days); System.out.println("--------"); Month m2 = Month.JAN; System.out.println(m2); System.out.println(m2.getDays()); System.out.println(m2.days); System.out.println("--------"); } }
1951)
1952) 1953) 1954) 1955) 1956) 1957) 1958) 1959) 1960)
Example 3: class Test { enum A { CON1, CON2, CON3 { void test()
Core Java 1961) { 1962) System.out.println("CSCB-test"); 1963) } 1964) },CON4, CON5; 1965) 1966) void test() 1967) { 1968) System.out.println("test"); 1969) } 1970) } 1971) 1972) public static void main(String[] args) 1973) { 1974) A a1 = A.CON5; 1975) A a2 = A.CON1; 1976) A a3 = A.CON3; 1977) A a4 = A.CON4; 1978) System.out.println(a1); 1979) System.out.println(a2); 1980) System.out.println(a3); 1981) System.out.println(a4); 1982) a1.test(); 1983) a2.test(); 1984) a3.test();//this line will call the method inside it in the séance CON3 1985) a4.test(); 1986) } 1987) } 1988) 1989)
Output
1990) 1991) 1992) 1993) 1994) 1995) 1996) 1997) 1998)
CON5 CON1 CON3 CON4 test test CSCB-test test
1999)
Array
2000) 2001) Array is a collection of similar type of elements that, all elements are stored in same memory location. We can store the fixed number of elements in the array( i mean the mentioned size of elements). 2002) There are two types of array 2003) One dimensional array 2004) Multi dimensional array 2005) To check the size of array 2006) Syntax : arrayName.length 2007) 2008) Declaring Array 2009) One Dimensional Array : dataType variable[ ] = new dataType[size]; 2010) Example :
Core Java 2011) int[ ] a = new int[5]; 2012) int [ ]a = new int[5]; 2013) int a[ ] = new int[5]; 2014) int a[ ] = {1,2,3,4,5,6}; //Declaration & initialization in a single line 2015) Two dimensional array : dataType variable[ ][ ] = new dataType[row-size][columnsize]; 2016) Example : 2017) int[ ][ ] a = new int[3][3]; 2018) int [ ]a[ ] = new int[3][3]; 2019) int a[ ][ ] = new int[3][3]; 2020) int [ ][ ]a = new int[3][3]; 2021) int a[ ][ ] = {{1,2,3},{4,5,6}}; 2022) 2023) Jagged Array 2024) Array in which number of columns different in each row called jagged array. 2025) int a[ ][ ] = new int[4][ ]; 2026) 2027) a[0] = new int[5]; 2028) a[1] = new int[2]; 2029) a[2] = new int[1]; 2030) a[3] = new int[4]; 2031) 2032) a[0]th row contains 5-columns 2033) a[1]th row contains 2-columns 2034) a[2]th row contains 1-columns 2035) a[3]th row contains 4-columns 2036) 2037) Note : 2038) To check the size of array or to get the size of array 2039) arrayName.length 2040) To check the size of individual row of array 2041) arrayName[row-number].length 2042) public class Program 2043) { 2044) public static void main(String[] args) throws IOException { 2045) Scanner s = new Scanner(System.in); 2046) int a[][] = new int[3][]; 2047) a[0]=new int[4]; 2048) a[1]=new int[1]; 2049) a[2]=new int[2]; 2050) for(int i=0;i