Core Java
Core Java
Core Java
CORE JAVA
Page 1 of 108
CONTENTS
SL. DATE TOPICS TAUGHT PAGE
BIBLIOGRAPHY 108
Page 2 of 108
4 JUNE 2019 HK
3. TYPES OF SOFTWARES:
PLATFORM INDEPENDENT
Page 3 of 108
JAVA
1. It is purely Object Oriented Programming language.
2. It was created by James Gosling in year 1995 for Sun Micro Systems.
3. It is a platform independent programming language that follows the logic – Write once, Run
Everywhere.
4. It is categorized in 3 types:
a. JSE JAVA STANDARD EDITION FOR DESKTOP AND STANDALONES
b. JEE JAVA ENTERPRISE EDITION FOR WEBSITE, DESKTOP AND DISTRIBUTED
c. JME JAVA MICRO EDITION FOR MOBILE APPLICATIONS
JSE
1. It is the standard module of Java, which contains all minimum requirements for application/ java.
2. Using it, we can build desktop applications/ stand-alone applications.
JEE OR J2E
WEB APPLICATION
Here, multiple clients are connected to 1 system.
DISTRIBUTED APPLICATION
Here, software based clients can be connected to the software based server.
Server software can be connected to the client in web application.
JME
It is used to build mobile applications.
FEATURES OF JAVA:
1. SIMPLE
It is purely syntax based, so simple. Java syntax are simple and easy to write and understand.
2. OOPS
3. ROBOSTIC
4. SECURE
5. PLATFORM INDEPENDENT
6. MULTI-THREADING
7. INTERPRETED
8. ARCHITECTURAL NEUTRAL
9. DYNAMIC
10. DISTRIBUTED
11. MULTI-MEDIA
12. PORTABLE
Page 4 of 108
Object Oriented Programming Synopsis (OOPS):
1. CLASS:
a. Collection of similar types of objects.
b. It is a container of data member, behavior and functionality.
2. OBJECT:
a. It is an instance of a class.
b. It can access behavior and member of class.
3. DATA ABSTRACTION:
a. It means displaying necessary information and hiding the background/ code details to
end-user.
b. Due to abstraction, OOPS support security and prevent hacking.
4. DATA HIDING:
a. The internal details are never accessed by outsider directly.
b. Provides security. Only validate users can access the internal details.
5. ENCAPSULATION:
Wrapping and binding code into a single unit execute a specific task.
6. INHERITANCE:
a. All features are available in one software.
b. Creating a new software from existing software/ creating a new class from existing class with
acquiring all properties of existing class.
Page 5 of 108
05 JUNE 2019 HK
1. CHARACTERS:
i. a to z ASCII values : 97 to 122
ii. A to Z ASCII values : 65 to 90
iii. 0 to 9 ASCII values : 48 to 57
2. KEYWORDS (53):
i. MODIFIERS (11): iv. super
i. private iv. DATATYPE (8):
ii. protected i. byte
iii. public ii. char
iv. static iii. short
v. final iv. int
vi. abstract v. long
vii. volatile vi. float
viii. transient vii. double
ix. strictfp viii. boolean
x. synchronized v. CLASS (6):
xi. native i. class
ii. CONTROL STATEMENTS (11): ii. interface
i. if iii. import
ii. else iv. package
iii. switch v. extends
iv. case vi. implements
v. default vi. EXCEPTION (6):
vi. break i. try
vii. continue ii. catch
viii. while iii. throw
ix. do iv. throws
x. for v. finally
xi. return vi. assert
iii. OBJECT (4): vii. NON-RETURN TYPE (1):
i. new i. void
ii. instanceof viii. ENUMERATION (1):
iii. this i. enum
Page 6 of 108
IDENTIFIERS OR VARIABLES:
A name in java program is called as an identifier. It can be a method’s name, class’s name or a
variable’s name.
DATATYPES:
It defines the type of data a variable can store.
DATATYPES
PRIMITIVE NON-PRIMITIVE
NUMERIC NON-NUMERIC
Example:
class Demo
{
private int a;
public int b;
protected int c;
int d;
}
Page 7 of 108
NOTE:
1. ‘a’ can be accessed within same class but not outside the class, not even using the object.
2. ‘b’ can be accessed anywhere within the class, within child class and outside the class (using
object).
3. ‘c’ can be accessed within same class. It is also accessible in child class.
4. ‘d’ has same properties as ‘a’, except the fact that it cannot be accessed outside current package.
CAMEL RULE:
This rule defines the restrictions for naming of classes, methods, instances and variables.
1. CLASS and INTERFACE:
a. First character of class name should be in upper case (as in Java library).
Example: Scanner class.
b. If we take multiple words as one name, first letter of each word should be capital.
Example: BufferedReader class.
2. METHOD:
a. First character of method name should be in lower case (as in Java library).
Example: main()
b. If we take multiple words as one name, first letter of each word (after first word) should be
capital.
Example: myMethod()
3. VARIABLES:
a. Whole name should be in lower case.
Example: name
4. CONSTANTS:
a. Whole name should be in upper case.
Example: PI
OPERATORS:
EXPRESSION: It is a combination of operands and operators.
OPERATOR: It is a symbol which indicates the compiler to perform certain mathematical/ logical
operation.
OPERATORS IN JAVA:
There are 3 types of operators depending on the number of operands:
a. Unary operator
b. Binary operator
c. Ternary operator
Output:
6
Output:
6
5
Output:
6
6
Eg-4: int a=5, b;
b=++a + a++;
System.out.println(a);
System.out.println(b);
Output:
7
12
Explanation: b = ++a + a++;
6 6 values at the time of evaluation
++a will be evaluated: value of a will be incremented to 6 and the value 6 is used in the
expression.
a++ will be evaluated: current value of a, 6, will be used in expression, and then the value of
a is incremented to 7.
Page 9 of 108
Eg-6: int a=2, b;
b = ++a + ++a + ++a + ++a;
System.out.println(a);
System.out.println(b);
Output:
6
18
Explanation:
b = ++a + ++a + ++a + ++a;
3 4 5 6 values at the time of evaluation
Output:
5
7
Explanation:
b = ++a * ++a - ++a;
3 * 4 - 5 values at the time of evaluation
b= 12 - 5 = 7 (* and /) before (+ and -)
Output:
B
Eg-9: double d= 8.9;
d++;
System.out.println(d);
Output:
9.9
Output:
Compile time error: bad operand type boolean for unary operator ‘++’.
Output:
Compile time error: unexpected type
Required: variable Found: value
Page 10 of 108
Eg-12: int x=10, y;
y=++(++x);
System.out.println(y);
Output:
Compile time error: unexpected type
Required: variable Found: value
Output:
11
Output:
Compile time error: incompatible types: possible lossy conversion from int to byte.
Output:
11
Note: 1. All mathematical operations on any 2 operands result in :
Max( int, type_A, type_B)
2. In increment/ decrement, internal typecasting is done automatically.
Page 11 of 108
06 JUNE 2019 HK
Note: If we apply any arithmetic operation between two variables/ values a & b, then, the result will be:
Maximum(int, type_a, type_b).
char > byte > short > int > long > float > double
Note:
1. char + char = int
2. char + byte = int
3. char + short = int
4. char + int = int
5. char + long = long
6. char + float = float
7. char + double = double
8. byte + byte = int
9. byte + short = int
10. byte + int = int
11. byte + long = long
12. byte + float = float
13. byte + double = double
14. short + short = int
15. short + int = int
16. short + long = long
17. short + float = float
18. short + double = double
19. int + int = int
20. int + long = long
21. int + float = float
22. int + double = double
23. long + long = long
24. long + float = float
25. long + double = double
26. float + float = float
27. float + double = double
28. double + double = double
Page 12 of 108
VIEWING THE FUNCTION AND CONSTANTS LIST OF A CLASS:
>>>javap <class full path>
Eg: >>>javap java.lang.Integer
>>>javap java.lang.Double
>>>javap java.lang.Long
and so on…
java.lang.Integer
java.lang.Float
Page 13 of 108
Note: After seeing the java.lang.Integer Class and java.lang.Float Class (after enlarging the
screenshots), it should be noticed that the Float class contains the constants:
which are not available in Integer class. This is the reason why ArithmeticException (/ by zero)
occurs when both operands are integers.
While, the same operations result in Infinity, -Infinity and NaN when at least one of the operands is a
float.
RELATIONAL OPERATORS:
> < <= >=
These are used for comparison of values. The result is always a boolean (true OR false).
10 < 20 true
‘a’ < 10 false
‘a’ < 97.6 true
‘a’ < ‘A’ true
Note: 1. These operators are legal for all primitive datatypes except boolean.
2. Strings can’t be compared using these operators.
BITWISE OPERATORS:
& | ^
5 & 4 4
5 | 4 5
5 ^ 4 1
5 & 4 : 1 & 1 = 1
5 00000101 1 & 0 = 0
4 00000100 0 & 1 = 0
Result 00000100 0 & 0 = 0
5 | 4 : 1 | 1 = 1
5 00000101 1 | 0 = 1
4 00000100 0 | 1 = 1
Result 00000101 0 | 0 = 0
5 ^ 4 : 1 ^ 1 = 0
5 00000101 1 ^ 0 = 1
4 00000100 0 ^ 1 = 1
Result 00000001 0 ^ 0 = 0
Page 14 of 108
SHIFT OPERATORS:
>> <<
5 << 2 20 5 * 22 a << b = a * 2b
5 >> 2 1 5 / 22 a >> b = a / 2b
-5 << 2 -20 -5 * 22
EQUALITY OPERATOR:
==
‘a’ == 97 true
‘a’ == 97.00 true
false == false true
ASSIGNMENT OPERATORS:
= += -= *= /= %= >>= <<=
Types of expressions:
1. Single: a = 10;
2. Chained: a = b = c = 10;
3. Compound: a += b *= c /= 2;
Expression Result
b+c+d+a 60xyz
b+c+a+d 30xyz30
b+a+c+d 10xyz2030
a+b+c+d xyz102030
Page 15 of 108
NEW OPERATOR:
new
1. It creates current class object.
2. It is used for allocation of memory.
Eg-1:
class Demo
{
void show()
{
System.out.println(“Hi”);
}
Output:
Hi
Eg-2:
class X
{
void show()
{
System.out.println(“class X”);
}
}
class Y
{
public static void main(String args[])
{
X obj = new X();
obj.show();
}
}
Output:
class X
Page 16 of 108
07 JUNE 2019 HK
INSTANCEOF OPERATOR:
instanceof
It is used to check the type of object.
Eg:
class Demo
{
public static void main(String args[])
{
Demo d = new Demo();
System.out.println(d instanceof Demo);
}
}
Output:
true
CONDITIONAL OPERATOR:
?:
It is the only ternary operator in Java.
Output:
Greatest number : 20
Output:
20
Page 17 of 108
JVM ARCHITECTURE
JAVAC COMPILE
MEMORY
METHOD HEAP STACK PC REGISTER NATIVE
AREA AREA AREA AREA
CLASSES OBJECTS THREADS REGISTER VARIABLES THREADS
EXECUTION ENGINE
After compilation of [.java] file, compiler generates the bytecode or java program files. Number of
[.class] files are generated depending upon the number of classes in the [.java] program. The Class
Loader loads all the [.class] files in the JVM. All JVMs include 1 class loader that is embedded in
the virtual machine.
CLASS LOADER:
1. Loading: Loads all the [.class] files from system into JVM. If a [.class] file is not found, it raises
exceptions like: ClassNotFoundException
NoClassDefinitionFoundException
a. Bootstrap class loader: Bootstrap ClassLoader is responsible for loading
standard JDK class files from rt.jar and it is parent of all class loaders in Java.
Path of the loader: C:\Program Files\Java\jdk1.8.0_201\jre\lib
MEMORY:
1. Method Area : It is the class memory, where all static members are allocated memory.
2. Heap Area : Objects and Non-static members are allocated memory here.
3. Stack Area : All local members, methods (main) and garbage collector are allocated
memory here.
4. Native Area : Native methods are allocated memory here.
5. PC Register : According to multiple threads, multiple PC registers are created which hold
address of current execution of instruction.
Page 19 of 108
Q1: Input two numbers and interchange them using XOR operator.
Ans:
Page 20 of 108
Q3: Input the radius of a circle, length and breadth of a rectangle and find the areas.
Ans:
Q4: Input two numbers and interchange them using a third variable.
Ans:
Page 21 of 108
08 JUNE 2019 HK
CONDITIONAL STATEMENTS:
1. if
Syntax:
if ( condition/ boolean )
{
//statements
}
If the condition/ Boolean is evaluated as “true”, then, the statements in the if-block will be
executed.
Example-1: if(10>5)
{
System.out.println(“10 is greater than 5.”);
}
Example-2: if(true)
{
System.out.println(“the condition is true !!”);
}
Note: If the if-block contains only one statement, then the parenthesis are not necessary.
Example-3: if(10>5)
System.out.println(“No parenthesis !!”);
2. if – else
Sysntax:
if ( condition/ boolean)
{
//statement_block-1
}
else
{
//statement_block-2
}
If the condition/ Boolean is evaluated as “true”, then, the statement_block-1 will be executed.
If the condition/ Boolean is evaluated as “false”, then, the statement_block-2 will be executed.
Note:
Ex: if(1==1)
System.out.println(“1”);
System.out.println(“2”);
else
System.out.println(“1”);
Page 22 of 108
3. Multiple if ( if – else ladder )
syntax:
if(cond_1)
{
//statements_1
}
else if(cond_2)
{
//statements_2
}
else if(cond_3)
{
//statements_3
}
else if(cond_4)
…
…
…
else if(cond_n)
{
//statements_n
}
else
{
//statements_e
}
The compiler checks the first condition, cond_1. If cond_1 is evaluated as true, it executes the
statements within the following block, statements_1. But if cond_1 is evaluated false, it goes to
next if condition, cond_2 in the else part of the first condition. Likewise, it checks every condition
till a condition is evaluated true. If all the conditions are evaluated as false, then final else block
statements, statements_e will get executed.
4. Nested if
Syntax:
if(cond_11)
{
if(cond_12)
{
if(cond_1n)
{
//statements
}
else
{
//statements
}
}
else
{
//statements
}
Page 23 of 108
}
else
{
if(cond_21)
{
if(cond_22)
{
if(cond_2m)
{
//statements
}
}
Here, if cond_11 is evaluated true, control moves to inner condition, cond_12 and so on till
the conditions are evaluated as true. When the condition is evaluated as false, the control
moves to the else part of the if statement, if exists. If cond_11 is evaluated false, then the
control moves to else part and checks for cond_21. And the same process follows and the
control moves deeper into the block till the conditions are evaluated as true.
Q1: Input a number and display whether the number is odd or even.
Ans:
Page 24 of 108
Q2: Input two numbers and display the greatest one.
Ans:
Q3: Input a year and display if the year is a leap year or not. Use logical operators. (&& , || , ! ).
Ans:
Page 25 of 108
Q4: Input a character and check if it is a vowel or not.
Ans:
Page 26 of 108
Q6: Input five numbers and display them.
Ans:
Page 27 of 108
Q8: Input a number and a choice.
If choice is 1, then display whether the number is +ve, -ve or zero.
2, then display whether the number is odd or even.
Ans:
Page 28 of 108
5. switch STATEMENT
Syntax:
switch(int/char)
{
case 1 : //statements_1; break;
case 2 : //statements_2;break;
case 3 : //statements_3;break;
.
.
.
case n : //statements_n;break;
default : //statements_d
}
Here, the integer/ character written in the brackets of switch statement is checked for EQUALITY
with the values in the cases. The cases may not be sorted. The default statement can be placed
anywhere within switch block. Only values can be used in case statements for equality check.
When the integer/ character is successfully matched with any of the test case values, the control
moves to the statement block and executes all the statements even in other test cases till either
break statement is encountered or end of block. Block statement is optional. The break
statement in last case is not necessary if there is no default statement.
Output:
1
-1
1000
Output:
1
Page 29 of 108
Ex-3: int a=1, b=1, c=-1, d=1000;
switch(a)
{
case c : System.out.println(“b”);
case b : System.out.println(“c”);
case d : System.out.println(“d”);
}
Output:
Error : non-values in case statements. Expected : values
Output:
Error : only integer and character variables are allowed in switch statement.
Ex-9: switch(1)
{
case 1 : System.out.println(“1”);break;
case -1 : System.out.println(“-1”);break;
case 1000 : System.out.println(“1000”);
}
Output:
1
1. for LOOP:
Syntax:
for(initialization; condition; updatation)
{
//statements
}
Ex:
for(int i=1; i<=5; i++)
System.out.println(i);
Output:
1
2
3
4
5
2. while LOOP:
Syntax:
initialization;
while(condition)
{
//statements and updatation
}
Page 31 of 108
Ex:
int i=1;
while(i<=5)
{
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
3. do...while LOOP:
Syntax:
initialization;
do{
//statements and updatation
}while(condition);
Output:
1
2
3
4
5
Note: The do...while block will be executed at least once even if the condition is false from
beginning.
NESTING OF LOOPS:
A loop within another is called nesting of loop.
Ex: for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
System.out.print(i+j+” “);
Output:
2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9 6 7 8 9 10
INFINITE LOOP:
A loop that iterates forever is called an infinite loop.
Applications: 1. Gaming
2. Antivirus
Ex: for( ; ; ) while(true) do{
{ } { } }while(true);
Page 32 of 108
Q1: Write a program to print the following pattern:
11115
222210
333315 ...
Ans:
Page 33 of 108
Q3: Write a program to print the following pattern:
12345
1234
123
12
1
Ans:
Page 34 of 108
Q5: Write a program to print the following pattern:
1
22
333
4444
55555
Ans:
Page 35 of 108
Q7: Write a program to print all prime numbers from 1 to n.
Ans:
Page 36 of 108
11 JUNE 2019 HK
Q1: Input a number and check whether the number is Armstrong number or not.
Ans:
Q2: Input a number and check whether the number is palindrome or not.
Ans:
Page 37 of 108
Q3: Write a program to print Fibonacci series.
Ans:
Page 38 of 108
Q5: Input 5 numbers into an array and find the smallest and largest.
Ans:
Page 39 of 108
Q7: Input five numbers in an array. Display the value in ascending order.
Ans:
Page 40 of 108
Q9: Write a program to delete an element from an array.
Ans:
ARRAY
1. It is a collection of similar types of data.
2. It is called linear data structure.
3. It allocates contiguous memory locations.
4. Indexing starts from zero(0).
TYPES OF ARRAY:
a. Single Dimensional Array:
Syntax: datatype name[] = new datatype[size];
Ex: int a[] = new int[10];
b. Multidimensional Array:
Syntax: datatype name[][] = new datatype[row_size][col_size];
Ex: int a[][] = new int[5][5];
Page 41 of 108
COMMAND LINE ARGUMENT
The Java command line arguments are the argument passed at the time of execution. These arguments
are received from the console directly and can be used as an input.
NOTE:
1. The arguments passed in the console can be accessed using the args[] variable.
2. The arguments are by default treated as strings, and required to be converted into other datatypes
for specific operations.
Page 42 of 108
LENGTH PROPERTY:
length is a property used to find number of elements in an array of unknown size.
Syntax : int var = arr_name.length;
Ex: int len = myArray.length;
Example:
PARSING:
It is a method of converting a string to another datatype.
Syntax: datatype var = wrapper_class.parseDatatype(string_variable);
Ex: int a = Integer.parseInteger(args[0]); //in netbeans
int a = Integer.parseInt(args[0]); //in Java 1.8(Notepad)
Example:
Page 43 of 108
valueOf() FUNCTION:
This method is present in all Wrapper classes except java.lang.Boolean.
This method is similar to parse method.
Syntax: datatype var = Wrapper_class.valueOf(string_variable);
Ex: int d = Integer.valueOf(“5”);
Example:
for-EACH LOOP:
This loop is used when the size of the collection is not known.
This loop can be used only for accessing and modifying every element of the collection.
Syntax: for(datatype var : collection_name)
{ //statements }
Example:
Page 44 of 108
12 JUNE 2019 HK
JAGGED ARRAY:
Example:
Page 45 of 108
STRINGS
String is basically an object that represents sequence of character values.
An array of character works same as Java String.
Page 46 of 108
Explanation:
1. When ‘a’ was created with value “x”, a new literal constant “x” was created in String Constant Pool,
and the reference was returned.
2. When ‘b’ was created with same value “x”, JVM searched the String Constant Pool. There already
a literal with same value was present. So, no new literal was created, rather, b was assigned the
same reference as ‘a’.
3. Variables ‘a’ and ‘b’ have been created using string literals, hence, comparing:
a. a==b true Same reference
b. a.equals(b) true Same values of literals
c. a.hashCode()==b.hashCode() true Same address of literals
4. When value of ‘a’ was changed from “x” to “xy”, a new literal was created in String Constant Pool
and the reference was returned. Hence, the reference is changed. The value is also changed to
“xy”. And lastly, as a new literal is created, and allotted a different memory, the hashCode too
changes from the initial values. Now, ‘b’ is the initial copy of ‘a’. Now, comparing:
a. a==b false Different references
b. a.equals(b) false Different values of literals
c. a.hashCode()==b.hashCode() false Different address of literals
5. Now, using the new keyword, ‘c’ and ‘d’ are created with values “x” each. As this literal is already
present in the String Constant Pool, no new literal is created, hence both hashCodes are same. But
as they are created using new keyword, they have different references. And lastly, they both have
same values. Now comparing:
a. c==d false Different references
b. c.equals(d) true Same values of literals
c. c.hashCode()==d.hashCode() true Same address of literals
6. When value of ‘c’ was changed from “x” to “xy”, a new literal was not created in String Constant
Pool and the previous reference of ‘a’ was returned. Hence, the reference of ‘c’ is changed. The
value is also changed to “xy”. And lastly, as the value of the string is changed being allotted a
different memory, the hashCode too changes from the initial values. Now, ‘d’ is the initial copy of
‘c’. Now, comparing:
a. c==d false Different references, like earlier
b. c.equals(d) false Different values of literals
c. c.hashCode()==d.hashCode() false Different address of literals
7. Two new variables ‘g’ and ‘h’ are created with values “xy” and “x y”. ‘g’ has value that already
exists in String Constant Pool. So, the same hashCode of ‘a’ and ‘c’ is allotted to it. But as it is
created using new keyword, this has a different reference with respect to that stored in ‘a’ or ‘c’.
Note:
1. If two String objects have same literal values, then their hashCodes must be same. Reverse is not
true.
2. If two objects have same references, then their literal values must be same. Reverse is not true.
Page 47 of 108
STRING FUNCTIONS:
String str = “abcdef”; char ch[7];
3. getChars() : It is used to extract characters from one string and to store them in another.
Syntax:
char var[] = String_var.getChars(src_beg, src_end, dst, dst_beg);
src_beg : Beginning position in source String
src_end : Ending position in source string
dst : Destination string, where the substring is to be put
dst_beg : The starting position in Destination string where the substring is to be put
Ex : s.getChars(1, 3, ch, 4); //“ bc”
5. compareTo() : compares two strings and returns the difference of first mis-match.
Syntax:
int var = str_1.compareTo(str_2);
Note: difference value = chr_1 – chr_2
where chr_1 is the character in str_1 where first mis-match occurs.
and chr_2 is the character in str_2 where first mis-match occurs.
Ex : int diff = “abcd”.compareTo(“ABCD”); //‘a’ – ‘A’ = 32
int dif = “aBCD”.compareTo(“abcd”); //‘B’ – ‘b’ = -32
int d = “abcd”.compareTo(“abcd”); //‘a’ – ‘a’ = 0
(To Be Continued...)
Page 48 of 108
13 JUNE 2019 HK
7. startsWith() : Checks whether the given string starts at the given position in parent string.
It matches whole sub-string in the parent string, not just first character.
Syntax:
boolean var = parent_str.startsWith(sub_str,pos);
Ex : boolean b1 = “abcd”.startsWith(“abd”,0); //false
boolean b2 = “abcd”.startsWith(“abc”,0); //true
11. toLowerCase() : It returns a string after converting the parent string into lower case.
Syntax:
String var = parent_str.toLowerCase();
Ex : String str1 = “AbCdEf”.toLowerCase(); //“abcdef”
12. toUpperCase() : It returns a string after converting the parent string into upper case.
Syntax:
String var = parent_str.toUpperCase();
Ex : String str1 = “AbCdEf”.toUpperCase(); //“ABCDEF”
Page 49 of 108
14. split() : It returns an array of sub-strings, which are the parts of parent-string, split at
specified characters.
Syntax:
String var[] = parent_str.split(character);
Ex : String str[] = “a b c d”.split(“ ”); //{“a”,“b”,“c”,“d”}
String str[] = “a-b-c-d”.split(“-”); //{“a”,“b”,“c”,“d”}
String str[] = “arbrcrd”.split(“r”); //{“a”,“b”,“c”,“d”}
15. replace() : It is used to replace all occurrences of old_chr or old-str with new_chr or new_str.
Syntax:
String var = parent_string.replace(old_chr/old_str , new_chr/new_str);
Ex : String str1 = “abede”.replace(‘e’,‘c’); //“abcdc”
String str2 = “abyfy”.replace(“y”,“cde”); //“abcdefcde”
Note: Only a chr can replace another chr. Similarly, only a str can replace another str.
17. replaceFirst() : It replaces only the first occurrence of old_str with new_str.
Syntax:
String var = parent_str.replaceFirst(old_str, new_str);
Ex : String str1 = “acbcdc”.replaceFirst(“c”,“ab”); //“aabbcdc”
18. trim() : It removes all the extra spaces from both sides of a string.
Syntax:
String var = parent_str.trim();
Ex : String str1 = “ a b c d ”.trim(); //“a b c d”
Note: It doesn’t removes spaces between alpha-numeric characters.
19. contains() : It checks if the parent string contains the given sub-string or not.
Syntax:
boolean var = parent_str.contains(sub_str);
Ex : boolean b1 = “abcdef”.contains(“bcd”); //true
boolean b2 = “abcdef”.contains(“bdc”); //false
Page 50 of 108
MUTABLE and IMMUTABLE OBJECTS:
STRINGBUFFER CLASS:
StringBuffer class is similar to the String class which provides much functionality than the String class.
A StringBuffer class object is a growable and writable character sequence.
Declaration Syntax:
StringBuffer FUNCTIONS:
2. capacity() : It returns the maximum number of characters which can be stored in it.
Ex:
int var1 = sb1.capacity(); //16
int var2 = sb2.capacity(); //19
Note: The default value of capacity is 16, (if declared according to Method_1);
While using Method_2, capacity is initialized with 16+length_of_agrument.
3. ensureCapacity(): It increases the capacity according to the pattern, till it is greater than or
equal to the required capacity.
Syntax:
strbfr.ensureCapacity(cap);
Ex : sb1.ensureCapacity(18); //capacity of sb1 = 34
Page 51 of 108
4. charAt() : It returns the character at a specified position.
Syntax:
char var = SB_var.charAt(pos);
Ex : char ch = sb1.charAt(0); //1
5. getChars() : It is used to extract characters from one string and to store them in another.
Syntax:
char var[] = SB_var.getChars(src_beg, src_end, dst, dst_beg);
src_beg : Beginning position in source String
src_end : Ending position in source string
dst : Destination string, where the substring is to be put
dst_beg : The starting position in Destination string where the substring is to be put
Ex : sb1.getChars(0, 2, ch, 4); //“ 12”
6. append() : It is used to add characters at the end of existing string literal in StringBuffer object.
Syntax:
SB_var.append(any_datatype);
Ex : sb1.append(true); //“123true”
sb1.append(“true”); //“123true”
sb1.append(‘a’); //“123a”
sb1.append(1); //“1231”
sb1.append(1.0); //“1231.0”
...
Page 52 of 108
11. insert() : It is used to insert character(s) at any position in the literal.
Syntax:
SB_var.insert(pos, any_datatype);
Ex : sb1.insert(1,true); //“1true23”
sb1.insert(1,8); //“1823”
. . .
CLASS FUNDAMENTALS:
Java is a class-based programming language.
Defining a class :
class Class_name
{
static variables
static methods
constructor(s)
instance variables/ non-static variables
instance methods/ non-static methods
}
Method:
1. It is a self-content part of program which executes to perform a specific task.
2. Due to methods, program support modularization, where a large program is divided into smaller
sub-programs.
Advantages of methods:
1. Errors can be easily detected and corrected.
2. Ease to access code.
3. Program time complexity reduces due to execution of certain parts instead of whole program.
Page 53 of 108
Parts of a function/ method:
1. Declaration: It is the prototype which informs the compiler of the existence of the function.
Syntax:
access_specifier return_type function_name(arg_type_list);
Types of Methods:
1. static: These methods are declared using the keyword “static”.
a. These can be accessed using class-name, object-name.
b. These can also be accessed with direct function-name, but only within same class.
c. These are called class-level methods.
d. These can be accessed even before object creation.
e. A static method can access static variable and other static methods directly.
f. A static method cannot access instance variable/ instance method without object creation.
Page 54 of 108
17 JUNE 2019 HK
2. non-static: These methods are declared without using any “static” keyword.
a. These can only be accessed using object-name.
b. These are called object-level methods.
c. These can be accessed using objects, and hence, cannot be used before object creation.
d. An instance method can access all members of the class (static/ instance variable/ method).
e. These are allocated memory in heap area.
TYPES OF VARIABLES:
1. Local: These are the variables declared in methods, constructors, static blocks etc.
a. These are temporary.
b. They are created when their declaration is encountered.
c. These are created to meet the temporary requirements of users like loop variables.
d. These are stored in stacks.
e. These get destroyed when execution of their block ends.
f. These have higher priority than instance and static variables.
2. Instance: These are the variables declared in the class, without the use of “static” keyword.
a. The values of these variables can vary from object to object.
b. For every object, a separate copy of variable is created.
c. These can be initialized during class declaration.
d. These are created during object creation.
e. These are allocated memory in the heap area.
f. These are destroyed along with the object.
3. static: These are the variables declared in the class, using the “static” keyword.
a. The values are same for every object.
b. These are class-level members, declared using “static” keyword.
c. These are created at the time of loading the class in the ClassLoader.
d. These are destroyed at the end of program.
e. These can be initialized. If not initialized, they are initialized with the default values.
f. These can be accessed using object-name, class-name.
g. These can be accessed directly, only within same class.
Page 55 of 108
this KEYWORD:
When instance variable name and local variable names are same, the access priority will be given
to the local variable. To access the instance variable, we use the “this” keyword.
Example:
METHOD OVERLOADING:
This is a concept of polymorphism.
Here, same function is declared multiple times, having different argument lists.
Example:
Page 56 of 108
18 JUNE 2019 HK
CONSTRUCTOR:
1. It is a member function whose name is same as the class-name.
2. It doesn’t have a return type.
3. It is used to initialize the data members.
4. When an object is created, this is automatically called.
5. Other than initialization, any other task can also be done using it.
6. Instance initialization blocks (non-static blocks) are executed before the constructors.
TYPES OF CONSTRUCTORS:
1. Default constructor:
a. It takes no arguments.
Syntax:
class_name()
{
//statements
}
Ex : class Demo
{
Demo()
{
System.out.println(“Hi”);
}
public static void main(String args[])
{
Demo d = new Demo();
}
}
Output:
Hi
2. Parameterized constructor:
a. It takes argument.
Syntax:
class_name(arg_list)
{
//statements
}
Ex : class Demo
{
Demo(int i)
{
System.out.println(“Hi”+i);
}
public static void main(String args[])
{
Demo d = new Demo(5);
}
}
Output:
Hi5
Page 57 of 108
Note : If there is no constructor provided by the user, JVM automatically provides a default constructor.
The constructor provided by JVM contains only one statement in it : super();
Page 58 of 108
class Demo class Demo
{ {
Demo() Demo()
{ {
this(10); this(10); //No change
} }
Demo(int i) Demo(int i)
{ {
super();
} }
} }
class Demo class Demo
{ {
Demo() Demo()
{ {
this(10); this(10); //No change
} }
Demo(int i) Demo(int i)
{ {
super(); super(); //No change
} }
} }
class Demo class Demo
{ {
Demo() Demo()
{ {
super(); super(); //No change
} }
Demo(int i) Demo(int i)
{ {
super(); super(); //No change
} }
} }
class Demo class Demo
{ {
Demo() Demo()
{ {
this(); this(); //No change
} }
} }
//ERROR: Recursive constructor invocation
//this() again calls Demo()
class Demo class Demo
{ {
Demo() Demo()
{ {
this(10); this(10); //No change
} }
Demo(int i) Demo(int i)
{ {
this(); this(); //No change
} }
} }
//ERROR: Recursive constructor invocation
//this() calls Demo() AND
//this(10) calls Demo(int), forms cycle.
Page 59 of 108
class Demo class Demo
{ {
Demo() Demo()
{ {
System.out.println(“hi”); System.out.println(“hi”);
super(); super();
} }
} }
//ERROR: super() must be first statement
class Demo class Demo
{ {
Demo(int i) Demo(int i)
{ {
System.out.println(“hi”); System.out.println(“hi”);
this(); this();
} }
} }
//ERROR: this() must be first statement
class Demo class Demo
{ {
Demo(int i) Demo(int i)
{ {
this(); this();
super(); super();
} }
} }
//ERROR: super() must be first statement
//this() and super
Page 60 of 108
19 JUNE 2019 HK
BLOCKS IN JAVA:
Block is a group of related statements. Generally, blocks refer to the group of statements exterior to
all functions.
TYPES OF BLOCKS:
1. static: Any block declared using the keyword “static” is known as a static block.
a. These are class-level blocks.
b. Class related codes are implemented inside it.
c. It do not allows the non-static references, i.e., this and super.
d. It is executed implicitly when class is loaded in class loader.
e. It is allocated memory from method area.
f. If multiple blocks static blocks are declared, all the blocks are executed according to the
declaration order.
2. non-static: Any block declared without using the keyword “static” is known as a non-static block.
a. These are object-level blocks.
b. These execute according to object behavior or pre-task.
c. These are executed at the time of object creation, just before constructor execution.
d. If multiple blocks are declared, all blocks are executed according to the declaration order.
e. A non-static block which is used to initialize the data-members is known as the Instance
Initialization Block (IIB).
Example:
Page 61 of 108
Order of execution:
1. static blocks
2. non-static blocks
3. constructor
INHERITANCE:
Generating a new class from existing class with acquiring all the properties of existing class into new class
is called Inheritance.
The existing class is called: parent-class OR super-class OR base-class
The new class is called: child-class OR sub-class OR derived-class
TYPES OF INHERITANCE:
1. Single:
PARENT_CLASS
↓
CHILD_CLASS
2. Hierarchical:
PARENT_CLASS
CHILD_1 CHILD_2
3. Multilevel:
PARENT_CLASS
↓
INTERMEDIATE_PARENT_CLASS
↓
CHILD_CLASS
Page 62 of 108
4. Muliple: [NOT ALLOWED IN JAVA USING CLASS] [INTERFACE CONCEPT]
5. Hybrid: [NOT ALLOWED IN JAVA USING CLASS] [INTERFACE CONCEPT]
extends: It is used when one class is inherited from another class or when one interface is inherited
from another.
Note: A class can be inherited from an interface, but reverse is illegal (invalid).
Note:
1. Except Object class, which has no super-class, every class has one and only one direct super-
class.
2. In the absence of any other explicit super-class, every class is implicitly a subclass of Object class.
3. A super-class can have any number of sub-classes.
4. A class can have only one super-class, because Java doesn’t support multiple inheritance.
5. Constructor(s) of base class are not inherited, but they can be invoked from derived-class.
6. Private members of base class are not inherited. But the public and protected member functions of
base class can access the private members of the base-class.
Page 63 of 108
SINGLE INHERITANCE:
Structure: parent_class
↓
child_class
class Parent_class
{
//parent_class definition
}
Page 64 of 108
MULTILEVEL INHEERITANCE:
Structure: parent_class
↓
intermediate_parent
↓
child_class
class parent_class
{
//parent_class definition
}
Page 65 of 108
HIERARCHICAL INHERITANCE:
Structure: parent_class
child_class_1 child_class_2
class parent_class
{
//parent_class definition
}
Page 66 of 108
CONSTRUCTOR CALL ORDER IN MULTILEVEL INHERITENCE:
The constructor of base class executes before the execution of derived class constructor.
Example:
Page 67 of 108
20 JUNE 2019 HK
METHOD OVERRIDING:
The child-class gets all the methods and properties of the parent-class.
Sometimes, the child-class may not get satisfied with the parent-class’s method implementation.
Then, the child is allowed to redefine the methods based on requirements.
Note:
The parent-class method which has been redefined in the child-class, is called the overridden
method.
The child-class method which redefines the parent-class method is called the overriding method.
Example:
Page 68 of 108
INTERFACE:
1. It is a Java keyword using which Java supports 100% abstraction because all methods available are
by default abstract or public.
2. We cannot create objects of an interface directly.
3. We can declare object reference for interface.
4. An interface works like a skeleton of class where all reference or interface are implemented inside
child class.
5. All variables available inside interface are by default final.
Example:
Note:
1. obj1 is created using interface A’s reference and class B’s memory allocation(constructor).
2. obj2 is created using class B’s reference and class B’s memory allocation.
3. Both the ways of creating objects are legal and acceptable.
Page 69 of 108
MULTIPLE INHERITANCE:
Example:
Note: Even if the derived class inherits two functions with same prototype from two interfaces, it doesn’t
generate any error.
HYBRID INHERITANCE:
Example:
Page 70 of 108
final KEYWORD:
1. It is a keyword used as a modifier in java.
2. It is applicable for classes, methods and variables.
3. The variable’s value never changes when declared using final.
4. The method cannot be over-loaded or over-ridden which is declared as final.
5. A final class can’t be inherited.
Page 71 of 108
21 JUNE 2019 HK
ABSTRACT METHOD:
Syntax for declaring an abstract method:
abstract return_type func_name(arg_list);
ABSTRACT CLASS:
Syntax for declaring an abstract class:
abstract class class_name
{
//abstract methods and
//data members (instance & static) allowed
}
Example:
Page 72 of 108
22 JUNE 2019 HK
ERROR vs EXCEPTION:
Page 73 of 108
EXCEPTION:
An exception is an unwanted or unexpected event, which occurs during execution (run time) of a program,
which disrupts the normal flow of program’s instructions. Due to exceptions, program may terminate or
abort.Types of exceptions:
SL.NO. CHECKED EXCEPTION UNCHECKED EXCEPTION
1 These occurs at compile time. These occur at run-time.
2 These are called compile-time exceptions. These are called run-time exceptions.
3 These cannot be ignored during compilation. These can be ignored during compilation.
Page 74 of 108
try BLOCK:
try is a keyword used to define a block where all the code is written when there is a chance of exception.
Syntax:
try
{
//statements
}
catch BLOCK:
catch is a keyword used to define a block to handle the exceptions raised by the try block.
1. It always appears after try block.
2. The type of exception occurred in try block must match with the type of argument in the catch
block or to the super type.
3. For a single try block, multiple catch blocks may be defined.
Syntax:
catch(Exp_name var)
{
//statements
}
throw STATEMENT:
throw is a keyword used to explicitly throw an exception from any method or block of code.
Syntax:
throw Instance;
Ex : throw ArithmeticException(“/ by zero”);
throws STATEMENT:
throws is a keyword used in the signature (prototype) of a method to indicate that the method might throw
one of the listed type exceptions. The caller to these methods use try-catch block.
finally BLOCK:
finally is a keyword used to define a block which is guaranteed to execute whether exception occurs in
try block or not. A finally block always appears after try block.
Page 75 of 108
Example of basic try-catch-finally blocks:
Page 76 of 108
Note:
1. throws reports an exception even if no try block is used in the method.
2. throw reports an exception even if no exception practically exists.
3. finally is always executed, whether try block executes or catch block.
No error.
try
{
//statements
}
catch(Exception e)
{
//statements
}
8
try
{
//statements
}
catch(Exception e)
{
//statements
}
Page 78 of 108
No error.
try
{
//statements
}
finally
{
//statements
}
9
try
{
//statements
}
finally
{
//statements
}
No error.
try
{
//statements
}
catch(Exception e)
{
//statements
}
10
try
{
//statements
}
finally
{
//statements
}
No error.
try
{
//statements
}
finally
{
//statements
}
11
try
{
//statements
}
catch(Exception e)
{
//statements
}
Page 79 of 108
No error.
try
{
//statements
}
catch(Exception e)
{
//statements
}
finally
{
//statements
12
}
try
{
//statements
}
finally
{
//statements
}
No error.
try
{
//statements
}
finally
{
//statements
}
try
{
13
//statements
}
catch(Exception e)
{
//statements
}
finally
{
//statements
}
Page 80 of 108
error: 'try' without 'catch',
'finally' or resource declarations
try
{
//statements
}
try
{
//statements
}
14
catch(Exception e)
{
//statements
}
finally
{
//statements
}
No error.
try
{
//statements
}
catch(Exception e)
{
//statements
}
finally
{
//statements
15 }
try
{
//statements
}
catch(Exception e)
{
//statements
}
finally
{
//statements
}
try error: 'try' without 'catch',
{ 'finally' or resource declarations
16 //statements
}
Page 81 of 108
catch(Exception e) error: 'catch' without 'try'
{
17
//statements
}
finally error: 'catch' without 'try'
{
18
//statements
}
try error: 'finally' without 'try'
{
//statements
}
catch(Exception e)
{
19 //statements
}
System.out.println(“hi”);
finally
{
//statements
}
Page 82 of 108
24 JUNE 2019 HK
FILE HANDLING:
FILE: When some data is to be stored permanently, the data is stored in files in secondary memory.
When a small amount of data is to be stored, file is recommended.
When a large amount of data is to be stored, database is recommended.
File CLASS:
import java.io.File; //used to access the functions.
import java.io.IOException; //it is used with main() using the “throws” keyword
1. Constructor: Its used to create a logical file/directory.
Syntax:
1. File file_name = new File(String path_name);
Ex: File f1 = new File(“abcd”); //creates a new directory, logically
File f2 = new File(“x.txt”); //creates a new text file, logically
3. canRead(): It returns true if file is readable, and returns false if file is not readable.
Syntax:
boolean var = file_obj.canRead();
Ex: boolean b1 = f1.canRead(); //true
Page 83 of 108
4. canWrite(): It checks if any data can be written in the file.
Syntax:
boolean var = file_obj.canWrite();
Ex: boolean b2 = f1.canWrite(); //true
9. createNewFile(): It generates the physical file of the logical entity of file defined by file object.
Syntax:
1. boolean var = file_obj.createNewFile();
2. file_obj.createNewFile();
Ex: boolean b9 = f2.createNewFile(); //true
f3.createNewFile();
boolean b10 = f2.createNewFile(); //false, file already exists
Note: true is returned if file is created successfully.
false is returned if file couldn’t be created or if file already exists.
Page 84 of 108
10. delete(): It deletes the file/ directory defined by the file object.
Syntax:
1. boolean var = file_obj.delete();
2. file_obj.delete();
Ex: boolean b11 = f2.delete(); //true
f3.delete();
boolean b12 = f2.delete(); //false, file already deleted
Note: a. true is returned if file is deleted successfully.
b. false is returned if file couldn’t be deleted or if file has already been deleted.
c. A directory can only be deleted when it doesn’t contain any other file/ directory.
11. list(): It returns a list of all files and directories in the directory defined by the file object.
Syntax:
String var[] = file_obj.list();
12. mkdir(): It creates the physical existence of the directory, defined by the file object.
Syntax:
boolean var = file_obj.mkdir();
Ex: boolean b13 = f1.mkdir(); //true
boolean b14 = f1.mkdir(); //flase
Note: true is returned if directory is created successfully.
false is returned if directory couldn’t be created or if directory already exists.
FileWriter CLASS:
It is one of the classes used to write data into a file.
This class is used to write strings or text.
Functions:
File f = new File(“C:\\java1\\rohnak”,“x.txt”); char ch[]={‘a’,’b’,’c’};
f.createNewFile();
2. fw_obj.write(str);
Ex: fw1.write(“hi”); //“hi” is written
3. fw_obj.write(chr[]);
Ex: fw1.write(ch); //“abc” is written
Page 85 of 108
3. flush(): It is used to write the data buffered in the memory and has not been written yet.
It guarantees that all data has been written successfully.
Syntax:
fw_obj.flush();
Ex: fw1.flush();
FileReader CLASS:
It is used to read data/ text from a file.
Functions:
File f = new File(“C:\\java1\\rohnak”,“x.txt”); char ch;
2. read(): It returns a character in ASCII form. At the end of file, it returns -1.
Syntax:
int var = fr_obj.read();
OR char var = (char)fr_obj.read();
Ex: char ch = (char)fr1.read(); //a
Page 86 of 108
BufferedWriter CLASS:
It is used to write data/ text in a file.
It provides the FileWriter efficiency.
A file cannot be opened directly for writing, using the BufferedWriter. BufferedWriter object requires
a FileWriter object to write data.
Functions:
File f = new File(“C:\\java1\\rohnak”,“x.txt”);
char ch[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};
2. BW_obj.write(str,start_pos,no_of_chars);
Ex: bw1.write(“abcdefghij”,2,3); //“cde” will be written
3. BW_obj.write(chr[],start_pos,no_of_chars);
Ex: bw1.write(ch,1,2); //“bc”
4. flush(): It is used to write all the buffered unwritten data in the file.
Syntax:
BW_obj.flush();
Ex: bw1.flush();
Page 87 of 108
BufferedReader CLASS:
It is used to read data from file.
It provides the FileReader efficiency.
A file cannot be opened directly for reading, using the BufferedReader. BufferedReader object
requires a FileReader object to write data.
Functions:
File f = new File(“C:\\java1\\rohnak”,“x.txt”);
1. read(): It returns a character in ASCII form. At the end of file, it returns -1.
Syntax:
int var = BR_obj.read();
OR char var = (char)BR_obj.read();
Ex: char ch = (char)br1.read(); //‘a’
Page 88 of 108
PrintWriter CLASS:
It is used to write data into file.
Functions:
1. Constructor: It opens the file to write data.
Syntax:
1. PrintWriter pw_obj = new PrintWriter(file_path);
2. PrintWriter pw_obj = new PrintWriter(file_obj);
3. PrintWriter pw_obj = new PrintWriter(new FileWriter(file_path));
4. PrintWriter pw_obj = new PrintWriter(new FileWriter(file_obj));
3. println(): It writes any type if data, and then inserts a new line.
Syntax:
1. pw_obj.println(char_var);
2. pw_obj.println(int_var);
3. pw_obj.println(str);
Page 89 of 108
25 JUNE 2019 HK
Multi-Threading
Executing several tasks simultaneously is the concept of multi-tasking.
There are 2 types of multi-tasking:
1. Process Based Multi-Tasking
2. Thread Based Multi-Tasking
Whether Process based or Thread based, the main purpose of multi-tasking is to reduce response time and
improve performance of system.
The main areas of application:
1. Developing multimedia graphics
2. Developing video games
3. Developing animations
4. Developing web and application servers
...
Page 90 of 108
d. Thread Scheduler:
If multiple threads are waiting, then the order in which threads will execute is
decided by Thread Scheduler. It is a part of JVM and it’s exact behavior cannot be
expected. It is JVM Vender dependent. So, the order of execution of threads cannot
be expected. Hence, the exact output cannot be estimated.
Page 91 of 108
Note:
Page 92 of 108
3. start() always calls the default run() with no argument.
LIFECYCLE OF A THREAD:
if run() is
start() completed.
New Runnable
or or Running Dead
Born Ready
After starting a thread, if we try to restart same thread once again, a run-time exception will be displayed
saying: IllegalThreadStateException
Page 93 of 108
Runnable INTERFACE IMPLEMENTATION:
run() is the only available method.
THREAD PRIORITY:
Every thread has some priority.
It may be explicitly provided by the programmer or may be set by default by the JVM.
The valid range of thread priority is 1 to 10.
Where 1 is the thread with least priority and 10 is the thread with most priority.
Thread class defines the following constants to represent some standard priorities:
MIN_PRIORITY 1
NORM _PRIORITY 5
MAX_PRIORITY 10
Page 94 of 108
26 JUNE 2019 HK
1. yield(): It causes to pause the currently executing thread to give chance to remaining waiting
threads of same priority. If there are no waiting threads or all other threads have
lower priority than the current thread, then the current thread will continue to
execute.
Syntax:
thr_obj.yield();
Ex: thr1.yield();
2. sleep(): It is used to pause the current thread execution for given milliseconds.
Syntax:
thr_obj.sleep(time_in_ms);
Ex: thr1.sleep(1000); //1 second pause
3. join(): It keeps a thread waiting until the completion of some other thread.
Every join() throws InterruptedException which is a checked Exception.
Syntax:
thr_obj.join();
Ex: thr1.join();
Page 95 of 108
APPLET
It is a small web program using which we can build small web applications.
Using applet program, programmer is able to build graphics, audio and multi-media application.
Due to applet, java is known as “Hot Java”.
Applet program can be embedded with client browser to execute dynamic content and applet
program can directly run in browser or execute in the front-end port.
So, it takes less time of execution, also provide security.
INITIALIZE: First applet object create/ initialize when loaded into the browser.
STARTED: After initialization of an applet object, applet can start/ execute, or in other words, when
the browser is maximized, applet will maximize/ start.
DRAW: Here, all the graphical implementations are represented with applet.
The graphical components may be images or string messages.
DESTROY: When the applet/ bowser is closed, applet object is automatically destroyed.
Note: Initialization and destruction of applet object should execute only once for an applet program.
Page 96 of 108
HOW TO RUN APPLET:
1) HTML file:
Automatically run in browser.
<Applet code=”class_name” height=”height” width=”width”></Applet>
2) Applet Viewer:
>>>javac MyFile.java
>>>appletviewer MyFile.java
Example:
Page 97 of 108
paint(): It is the method used to represent the Text/ graphics on the Applet Screen.
This function is automatically executed when an applet starts.
Syntax:
public void paint(Graphics g);
3. setColor(): It is used to set the color used for the next graphics object.
Syntax:
setColor(java.awt.Color.<colorname>);
Ex: setColor(java.awt.Color.blue);
7. fillOval(): It is used to draw a solid oval filled with color in specified rectangle.
Syntax:
fillOval(x_pos, y_pos, width, height);
Ex: fillOval(80,80,30,30);
Note: The (x_pos,y_pos) is the coordinate of top-left corner of the rectangle.
Page 98 of 108
9. fillArc(): It is used to draw a solid arc filled with color.
Syntax:
fillOval(x_pos, y_pos, width, height, startAngle, arcAngle);
Ex: fillOval(80,80,30,30,0,-270);
Note: Positive arcAngle means anti-clockwise sweep, negative means clockwise.
Examples:
Page 99 of 108
Ex-2 Lines Arcs
Ex-3 Image
Ex: audio
Ex:
CHECKBOX:
Ex:
Ex:
Integer i = new Integer(100); //100
Integer j = new Integer(“100”); //100
Integer k = new Integer(“hi”); //error
Note: If any primitive type variable tends to store a string type value which is the same datatype’s type
value but enclosed in double quotes, then the compiler implicitly converts it in the datatype’s type.
Ex: Integer j = new Integer(“100”); //100
If any variable tends to store another datatype’s type value, then error is generated.
Ex: Integer t = new Integer(“1.1”); //error
AUTOBOXING vs UNBOXING:
AUTOBOXING UNBOXING
It refers to the conversion of primitive type value to It refers to the conversion of wrapper class type
the wrapper class type value. value to the primitive type value.
Ex: Ex:
int i = 10; Integer i = new Integer(10);
Integer j = new Integer(20); int j = 20;
j=i; //10 j=i; //10
DECLARING A PACKAGE:
Ex:
COMPILING A PACKAGE:
Ex:
>>>javac –d . R1.java
or
>>>javac –d C:/java1/rohnak/R1.java
RUNNING A PACKAGE:
Syntax:
>>>java package_name.Class_name
Ex:
>>>java A.R1
//Another program
import package_name;
//program body
Ex:
//program : “R2.java”
package B;
public class R2
{
public void display()
{
System.out.println("displayed.'");
}
}
//Program : “R3.java”
import B;
public class R3
{
public static void main(String args[])
{
R2 obj = new R2();
obj.display();
}
} //Output: displayed.
֍֍֍