Core java
Java - Overview
Java programming language was originally developed by
Sun MicroSystems which was initiated by "James Gosling" and
released in 1995 as core component of 'Sun Microsystem' Java
Platform (Java 1.0 [J2SE]).
The latest release of the Standard edition is JAVA SE 8.
The new J2 versions were renamed as Java SE, Java EE
and Java ME respectively. Java is guaranteed to be Write
Once, Run Anywhere.
Java is :
Object Oriented: In Java, everything is an Object. Java can
be easily extended since it is based on the Object model.
Platform Independent: Unlike many other programming
language including C and C++ , when java is compiled, It is
not compiled into platform specific machine, rather into
platform independent byte code. This byte code is
distributed over the web and interepted by the Virtual
Machine (JVM) on whichever platform it is being run on.
Simple: Java is designed to be easy to learn. If you
understand the basic concept of OOP Java, it would be
easy to master.
Secure: With Java`s secure feature it enables to develop
virus-free, tamper-free systems. Authentication techniques
are based on Public-key encryption.
Architecture-neutral: Java compiler generates an
architecture-neutral object file format, which makes the
compiles code executable on many processors,with the
presence of Java runtime system.
Core java
Portable: Being architecture-neutral and having no
implementation dependent aspects of the specification
makes java portable.
Multithreaded: With Java`s multithreaded feature it is
possible to write programs that can perform many tasks
simultaneously.
Interpreted: Java byte code is translated on the fly to
native machine instructions and is not stored anywhere.
High Performance: With the use of Just-In-Time compiles,
java enables high performance.
Distributed: Java is designed for the distributed
environment of the internet.
Dynamic: Java is considered to be more dynamic than C or
C++ since it is designed to adapt to an evolvimg
environment.
Tools You Will Need
You will need a Pentium 200-MHz computer with a
minimum of 64 MB of RAM (128 MB of RAM recommended).
You will also need the following softwares:
Linux 7.1 or Windows xp/7/8 operating system
Java JDK 8
Microsoft Notepad or any other text editor
How to Download Java
Download Java 1.8
Java SE Development Kit-8- download-oracle
Accept the license
Windows x86 for 32bit / Windows x64 for 64bit
Core java
Path setting of Java(Setting Environment Variable)
Assuming you have installed Java in C:\Program
Files\java\jdk directory:
Right click on "My Computer" and select " Properties".
Click the "Environment variables" button under the
"Advanced" tab.
Now, alter the 'Path' variable so that it also contains the
path to the Java executable. Example, if the path is curretly
set to 'C:\WINDOWS\SYSTEM32', then change your path to
read 'C:\WINDOWS\SYSTEM32; c:\Program
Files\java\jdk\bin';
Type javac in cmd to check whether java is installed or not
Type java -version is to check whether which versions it is
Java Editions:
Java SE (Standard Edition)
Use to develop standalone applications
Java EE (Enterprise Edition)
Use to develop web applications
Java ME (Micro Edition)
Use to develop Mobile Applications
Core java
Structure of the Java Program
class class_name
{
public static void main(String[ ] args)
{
//statement or code to execute
}
}
First Java Program:
Let us look at a simple code that would print the words
Hello World.
class MyFirstJavaProgram
{
/* This is my first java program. * This will print 'Hello World' as
the output */
public static void main(String[ ]args)
{
System.out.println("Hello World");
// prints Hello World
}
}
Core java
Let's look at how to save the file, compile and run the program.
Please follow the steps given below: Open notepad and add
the code as above.
Save the file as: MyFirstJavaProgram.java.
Open a command prompt window and go o the directory
where you saved the class. Assume it's D:\ Type 'javac
MyFirstJavaProgram.java ' and press enter to compile your
code.
If there are no errors in your code, the command prompt
will take you to the next line(Assumption : The path variable
is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.
D :> javac MyFirstJavaProgram.java
D:> java MyFirstJavaProgram
HelloWorld
To change the drive:
c:\users\user_name>D:
/* to change the path from c to d drive*/
D:\cd core_java
/* core_java is the folder in the drive where java program
saved */
D:\core_java>
Core java
Basic Syntax:
About Java programs, it is very important to keep in
mind the following points.
Case Sensitivity - Java is case sensitive, which means
identifier Hello and hello would have different meaning in
Java.
Class Names - For all class names, the first letter should be
in Upper Case. If several words are used to form a name of
the class, each inner word's first letter should be in Upper
Case.
Example class MyFirstJavaClass
Method Names - All method names should start with a
Lower Case letter. If several words are used to form the
name of the method, then each inner word's first letter
should be in Upper Case.
Example public void myMethodName()
Program File Name - Name of the program file should
exactly match the class name. When saving the file, you
should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the
file name and the class name do not match your program
will not compile).
Example : Assume 'MyFirstJavaProgram' is the class
name, then the file should be saved
as'MyFirstJavaProgram.java'
Core java
public static void main(String args[]) - Java program
processing starts from the main() method, which is a
mandatory part of every Java program.
Developing Java Program Includes 3 Steps
1. Source Code
2. Compilation
3. Execution
1. In Source code, creation step the java program is created
and saved in a file to the extension .java , this file contain only
java statements.
2. In Compilation stage, the source code is converted into
byte code by java compiler. The java compiler translates the java
statements into byte code statements and save it in a file with a
extension .class
Core java
The .class file is generated by java compiler. The byte code
statements is not in a machine executable formats.
3. In Execution stage, JVM executes the byte code and gives
the result of the byte code statement. While executing the byte
code the JVM translates the byte code into machine executable
formats with the help of JIT compiler.
The output of the JIT compiler is interpreted by the JVM to
give the result of Program. The .class file can be executed on
any operating system provided JRE`s installed on the system.
This concept is known as platform independent.
We cannot run the .class file without JRE, Hence it is dependent
on JRE.
While compiling if we get any error it is known as "Compile
time error", until we fix the compile time error the compiler will
not generate the .class file.
Any error occurring during the executable time, that is
known as "run time error", to fix the run time error go to the
source code, and do the required changes, recompile it and then
execute it.
JDK is a development kit containing the java compiler and
JRE and also few development tools needed for developing the
java applications.
We use text editor or integrated development environment
(IDE) tools to create the source code.
Example : 1. Text Editor:- Notepad, Notepad++,editplus
2. IDE :- Eclipse, Netbeans
Core java
Example
class Program
{
public static void main(String[] args)
{
System.out.println("JAVA");
System.out.println("J2EE");
}
}
E:\>cd core_java
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
JAVA
J2EE
E:\Core_Java>
Difference between print() and println()
println( ) it will print the value provided and cursor will go
to the next line.
print( ) it will also print the value provided and cursor will
remain in the same line.
Core java
Example:
class Program
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.print("World");
System.out.println("1234");
System.out.print("abcd");
}
}
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
Hello
World1234
abcd
E:\Core_Java>
Keywords in Java :
Keywords are Pre-defined reserved words which has already
have the certain meaning in java.
Total, we have 50 keywords available in java.
Example: public, static, int , abstract ,double................
Keywords cannot be used as your identifiers in java.
Identifiers:
Identifiers are the name provided by the programmer.
Example: Class_name, method_name, variable_name....
Core java
Rules
1. We can have alphanumeric values or alphabets.
Eg: abc123
abc
2. We can have combination of special characters.
Eg: abc@def123
3. We can`t start with numeric value.
Eg: 123 ----is not allowed
Datatypes:
There are eight primitive data types supported by Java.
Primitive data types are predefined by the language and named
by a keyword.
byte:
Byte data type is an 8-bit signed two's complement integer.
Byte data type is used to save space in large arrays, mainly in
place of integers, since a byte is four times smaller than an int.
Example: byte a = 100, byte b = -50;
short:
Short data type is a 16-bit signed two's complement integer.
Short data type can also be used to save memory as byte data
type, short is 2 times smaller than an int.
Example: short s= 10000, short r = -20000;
int:
int data type is a 32-bit signed two's complement integer.
int is generally used as the default data type for integral values
unless there is a concern about memory.
Example: int a = 100000, int b = -200000;
Core java
long:
Long data type is a 64-bit signed two's complement integer.
This type is used when a wider range than int is needed.
Example: int a = 100000L, int b = -200000L ;
float:
Float data type is a single-precision 32-bit IEEE 754 floating
point.
Float is mainly used to save memory in large arrays of floating
point numbers.
Example: float f1 = 234.5f;
double:
double data type is a double-precision 64-bit IEEE 754 floating
point.
This data type is generally used as the default data type for
decimal values, generally the default choice.
Example: double d1 = 123.4;
boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
char:
char data type is a single 16-bit Unicode character.
Char data type is used to store any character.
Example: char letterA ='A';
Core java
Variables:
Used to store an value.
Used to respresent an datatype.
Variable Declaration
Syntax :
Datatype variable_name ;
Example : int a;
Variable Initialization
Syntax :
Datatype variable_name = value;
Example : int a = 10;
Example :
class Program
{
public static void main(String[] args)
{
int a=21;
float b=5.5f; // f is compulsory
double c=12345;
long d=1234l;// l is not compulsory
char e='a';
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
Core java
}
}
Output :
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
21
5.5
12345.0
1234
a
E:\Core_Java>
Final Keyword in Java
If we declare variable as a final, we cant able to reinitialize value.
Example :
class Program
{
public static void main(String[] args)
{
final int pin=1234;
pin=4321;
System.out.println(pin);
}
}
Core java
Output :
E:\Core_Java>javac Program.java
Program.java:6: error: cannot assign a value to final variable pin
pin=4321;
^
1 error
E:\Core_Java>javac Program.java
Concatenation
By + (string concatenation) operator
Example :
class TestConcatenation1
{
public static void main(String args[])
{
System.out.println("Sachin"+" Tendulkar";);
}
}
Output
Sachin Tendulkar
Core java
Example :
class Program
{
public static void main(String args[])
{
System.out.println(50+30+"PMKK"+40+40);
}
}
Output :
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
80PMKK4040
E:\Core_Java>
Basic Operators
Java provides a rich set of operators to manipulate
variables. We can divide all the Java operators into the following
groups:
Arithmetic Operators
Conditional or Relational Operators
Logical Operators
Shorthand or Assignment Operators
Unary Operators
Ternary Operators
Bitwise Operators
Core java
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the
same way that they are used in algebra.
Operator Description
+ Addition - Adds values on either side of the operator
- Subtraction - Subtracts right hand operand from left
hand operand
* Multiplication - Multiplies values on either side of the
operator
/ Division - Divides left hand operand by right hand
operand
% Modulus - Divides left hand operand by right hand
operand and returns remainder
Example:
class Program
{
public static void main(String args[])
{
int a =10;
int b =20;
System.out.println("a + b = "+(a + b));
System.out.println("a - b = "+(a - b));
System.out.println("a * b = "+(a * b));
System.out.println("b / a = "+(b / a));
System.out.println("b % a = "+(b % a));
Core java
}
}
Output :
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
E:\Core_Java>
Conditional or Relational Operators
Operator Description
== Checks if the values of two operands are equal or
not, if yes then condition becomes true.
!= Checks if the values of two operands are equal or
not, if values are not equal then condition becomes
true.
> Checks if the value of left operand is greater than
the value of right operand, if yes then condition
becomes true.
< Checks if the value of left operand is less than the
value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater than
or equal to the value of right operand, if yes then
Core java
condition becomes true.
<= Checks if the value of left operand is less than or
equal to the value of right operand, if yes then
condition becomes true.
Example :
class Program
{
public static void main(String args[])
{
int a =10;
int b =20;
System.out.println("a == b = "+(a == b));
System.out.println("a != b = "+(a != b));
System.out.println("a > b = "+(a > b));
System.out.println("a < b = "+(a < b));
System.out.println("b >= a = "+(b >= a));
System.out.println("b <= a = "+(b <= a));
}
}
Output :
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
a == b = false
a != b = true
a > b = false
Core java
a < b = true
b >= a = true
b <= a = false
E:\Core_Java>
Logical Operators:
Operator Description
&& Called Logical AND operator. If both the operands are
non zero, then the condition becomes true.
|| Called Logical OR Operator. If any of the two
operands are non-zero, then the condition becomes
true.
! ! Called Logical NOT Operator. Use to reverses the
logical state of its operand.
Example :
class Program
{
public static void main(String args[])
{
boolean a =true;
boolean b =false;
System.out.println("a && b = "+(a&&b));
System.out.println("a || b = "+(a||b));
System.out.println("!(a && b) = "+!(a && b));
}
}
Core java
Output :
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
a && b = false
a || b = true
!(a && b) = true
E:\Core_Java>
Assignment Operator :
Operator Description
= Simple assignment operator, Assigns values from
right side operands to left side operand
+= Add AND assignment operator, It adds right
operand to the left operand and assign the result
to left operand
-= Subtract AND assignment operator, It subtracts
right operand from the left operand and assign the
result to left operand
*= Multiply AND assignment operator, It multiplies
right operand with the left operand and assign the
result to left operand
/= Divide AND assignment operator, It divides left
operand with the right operand and assign the
result to left operand
%= Modulus AND assignment operator, It takes
modulus using two operands and assign the
result to left operand
Core java
Example :
class Program
{
public static void main(String args[])
{
int a =10;
int b =20;
int c =0;
c = a + b;
System.out.println("c = a + b = "+ c );
c += a ;
System.out.println("c += a = "+ c );
c -= a ;
System.out.println("c -= a = "+ c );
c *= a ;
System.out.println("c *= a = "+ c );
a =10;
c =15;
c /= a ;
System.out.println("c /= a = "+ c );
a =10;
c =15;
c %= a ;
System.out.println("c %= a = "+ c );
}
}
Core java
Output :
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
c = a + b = 30
c += a = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a = 5
E:\Core_Java>
Unary Operator :
1. Increment
i. Pre Increment ( ++ x)
ii. Post Increment ( x++)
2. Decrement
i. Pre Decrement ( --x)
ii. Post Decrement ( x--)
Pre Increment : It will increment the value first then
assigns the value.
Post Increment : It will assign the value first then do the
increment operation
Pre Decrement : It will decrement the value first then
assigns the value.
Post Decrement : It will assign the value first then do the
Decrement operation
Core java
Example
class IncDec
{
public static void main(String[] args)
{
int a=10,b=11;
int r1=a++ + a++ + --a + a++;
System.out.println("The result is "+r1);
System.out.println("The value of a is "+a);
System.out.println("The value of b is "+b);
}
}
E:\PMKK\Core_Java>javac IncDec.java
E:\PMKK\Core_Java>java IncDec
The result is 43
The value of a is 12
The value of b is 11
E:\PMKK\Core_Java>
Core java
Conditional Statements:
1. if conditional statement
2. if-else conditional statement
3. if-else-if conditional statement
4. nested if-else conditional statement
5.switch case
1. if conditional statement
The Java if statement tests the condition. It executes the if
block if condition is true.
Syntax:
if(condition)
{
//code to be executed
}
Core java
//Java Program to demonstate the use of if statement.
public class IfExample
{
public static void main(String[] args)
{
//defining an 'age' variable
int age=20;
//checking the age
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
2. if-else conditional statement
The Java if-else statement also tests the condition. It
executes the if block if condition is true otherwise else block is
executed.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Core java
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample
{
public static void main(String[] args)
{
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
Core java
}
}
3. if-else-if conditional statement
The if-else-if ladder statement executes one condition from
multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
else
{
//code to be executed if all the conditions are false
}
Core java
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B g
rade, A grade and A+.
public class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
Core java
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
Core java
4. nested if-else conditional statement
The nested if statement represents the if block within
another if block. Here, the inner if block condition executes only
when outer if block condition is true.
Syntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
Core java
Email:- Page 32
Core java
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample
{
public static void main(String[] args)
{
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
}
}
}
Switch Statement
The Java switch statement executes one statement from
multiple conditions.
The switch statement works with byte, short, int, long,
enum types, String and some wrapper types like Byte,
Short, Int, and Long
There can be one or N number of case values for a switch
expression.
Core java
The case value must be of switch expression type only. The
case value must be literal or constant
The case values must be unique. In case of duplicate value,
it renders compile-time error.
Each case statement can have a break statement which is
optional. When control reaches to the break statement, it
jumps the control after the switch expression. If a break
statement is not found, it executes the next case.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
Core java
public class SwitchExample
{
public static void main(String[] args)
{
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number)
{
//Case statements
Core java
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Program to check Vowel or Consonant:
If the character is A, E, I, O, or U, it is vowel otherwise
consonant
public class SwitchVowelExample
{
public static void main(String[] args)
{
char ch='O';
switch(ch)
{
case 'a':
System.out.println("Vowel");
break;
case 'e':
System.out.println("Vowel");
break;
Core java
case 'i':
System.out.println("Vowel");
break;
case 'o':
System.out.println("Vowel");
break;
case 'u':
System.out.println("Vowel");
break;
case 'A':
System.out.println("Vowel");
break;
case 'E':
System.out.println("Vowel");
break;
case 'I':
System.out.println("Vowel");
break;
case 'O':
System.out.println("Vowel");
break;
case 'U':
System.out.println("Vowel");
break;
default:
System.out.println("Constant");
}
}}
Core java
Loops in JAVA
In programming languages, loops are used to execute a set
of instructions/functions repeatedly when some conditions
become true. There are three types of loops in java.
1. for loop
2. while loop
3. do-while loop
1. for loop
The Java for loop is a control flow statement that iterates a
part of the programs multiple times.
If the number of iteration is fixed, it is recommended to use for
loop.
Syntax:
for(initialization;condition;incr/decr)
{
//statement or code to be executed
}
1. Initialization: It is the initial condition which is executed
once when the loop starts. Here, we can initialize the
variable, or we can use an already initialized variable. It is
an optional condition.
2. Condition: It is the second condition which is executed
each time to test the condition of the loop. It continues
execution until the condition is false. It must return boolean
value either true or false. It is an optional condition.
Core java
3. Statement: The statement of the loop is executed each time
until the second condition is false.
4. Increment/Decrement: It increments or decrements the
variable value. It is an optional condition.
Core java
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample
{
public static void main(String[] args)
{
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Nested For Loop
If we have a for loop inside the another loop, it is known as
nested for loop. The inner loop executes completely whenever
outer loop executes.
Example:
public class NestedForExample
{
public static void main(String[] args)
{
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
Core java
}//end of i
}//end of j
}
}
Pyramid Example
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
*
**
***
****
*****
Core java
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be
infinitive for loop.
Syntax:
for(;;)
{
//code to be executed
}
Example:
//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
Core java
.
.
.
ctrl+c
Java While Loop
The Java while loop is used to iterate a part of the program
several times. If the number of iteration is not fixed, it is
recommended to use while loop.
Syntax:
while(condition)
{
//code to be executed
}
Core java
Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Java do-while Loop
The Java do-while loop is used to iterate a part of the
program several times. If the number of iteration is not fixed and
you must have to execute the loop at least once, it is
recommended to use do-while loop.
The Java do-while loop is executed at least once because
condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Core java
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Core java
Java Break Statement
When a break statement is encountered inside a loop, the
loop is immediately terminated and the program control resumes
at the next statement following the loop.
The Java break is used to break loop or switch statement. It
breaks the current flow of the program at specified condition. In
case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for
loop, while loop and do-while loop.
Syntax:
jump-statement;
break;
Core java
Java Break Statement with Loop
Example:
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Core java
Java Continue Statement
The continue statement is used in loop control structure
when you need to jump to the next iteration of the loop
immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It
continues the current flow of the program and skips the
remaining code at the specified condition. In case of an inner
loop, it continues the inner loop only.
We can use Java continue statement in all types of loops
such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
continue;
Example:
//Java Program to demonstrate the use of continue statement
//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
Core java
Output:
1
2
3
4
6
7
8
9
10
As you can see in the above output, 5 is not printed on the
console. It is because the loop is continued when it reaches to 5.
Java Comments
The java comments are statements that are not executed by
the compiler and interpreter. The comments can be used to
provide information or explanation about the variable, method,
class or any statement. It can also be used to hide program code
for specific time.
Types of Java Comments
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
Core java
1) Java Single Line Comment
The single line comment is used to comment only one line.
//This is single line comment
Example:
public class CommentExample1 {
public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}
2) Java Multi Line Comment
The multi line comment is used to comment multiple lines of
code.
Syntax:
/*
This
is
multi line
comment
*/
Core java
Methods in JAVA
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also
known as functions.
Why use methods?
To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with
the name of the method, followed by parentheses (). Java
provides some pre-defined methods, such as System.out.println(),
but you can also create your own methods to perform certain
actions:
Example
Create a method inside MyClass:
public class MyClass {
static void myMethod() {
// code to be executed
}
}
myMethod() is the name of the method
static means that the method belongs to the MyClass class
and not an object of the MyClass class. You will learn more
Core java
about objects and how to access methods through objects
later in this tutorial.
void means that this method does not have a return value.
You will learn more about return values later in this chapter
Call a Method
To call a method in Java, write the method's name followed
by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the
action), when it is called:
Example
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
Core java
A method can also be called multiple times:
Example
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
}
Methods with Parameters
Information can be passed to methods as parameter.
Parameters act as variables inside the method.
Parameters are specified after the method name, inside the
parentheses. You can add as many parameters as you want, just
separate them with a comma.
The following example has a method that takes
a String called fname as parameter. When the method is called,
we pass along a first name, which is used inside the method to
print the full name:
Core java
Example
public class MyClass {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
Multiple Parameters
Example
public class MyClass {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
Core java
Return Values
The void keyword, used in the examples above, indicates
that the method should not return a value. If you want the
method to return a value, you can use a primitive data type (such
as int, char, etc.) instead of void, and use the return keyword
inside the method:
Example
public class MyClass {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
This example returns the sum of a method's two parameters:
Example
public class MyClass {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
System.out.println(myMethod(5, 3));
}
}
Core java
You can also store the result in a variable (recommended, as it is
easier to read and maintain):
Example
public class MyClass {
static int myMethod(int x, int y) {
return x + y;
public static void main(String[] args) {
int z = myMethod(5, 3);
System.out.println(z);
A Method with If...Else
It is common to use if...else statements inside methods:
Example
public class MyClass {
// Create a checkAge() method with an integer variable called
age
static void checkAge(int age) {
Core java
// If age is less than 18, print "access denied"
if (age < 18) {
System.out.println("Access denied - You are not old
enough!");
// If age is greater than 18, print "access granted"
} else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an
age of 20
}
}
Core java
Java Arrays
Normally, an array is a collection of similar type of elements
which have a contiguous memory location.
Java array is an object which contains elements of a similar
data type. Additionally, The elements of an array are stored in a
contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a
Java array.
Array in Java is index-based, the first element of the array
is stored at the 0th index, 2nd element is stored on 1st index and
so on.
In Java, array is an object of a dynamically generated class.
Java array inherits the Object class, and implements the
Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. we can also create
single dimentional or multidimentional arrays in Java.
Advantages
o Code Optimization: It makes the code optimized, we can
retrieve or sort the data efficiently.
o Random access: We can get any data located at an index
position.
Core java
Disadvantages
o Size Limit: We can store only the fixed size of elements in
the array. It doesn't grow its size at runtime. To solve this
problem, collection framework is used in Java which grows
automatically.
Types of Array in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
o
Single Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar = new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are
going to declare, instantiate, initialize and traverse an array.
/Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
Core java
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array
together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Core java
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse
the same logic on any array.
Let's see the simple example to get the minimum number of
an array using a method.
//Java Program to demonstrate the way of passing an array
//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}
Core java
Returning Array from the Method
We can also return an array from the method in Java.
//Java Program to return an array from the method
class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Core java
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an
ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size
while traversing the array.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}
}
Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Core java
Java User Input (Scanner)
The Scanner class is used to get user input, and it is found
in the java.util package.
To use the Scanner class, create an object of the class and
use any of the available methods found in the Scanner class
documentation
Example
In our example, we will use the nextLine() method, which is used
to read Strings:
import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a
Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output
user input
}
}
Core java
Input Types
To read other types, look at the table below:
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Example
// Java program to read data of various types using Scanner
class.
import java.util.Scanner;
public class ScannerDemo1
{
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Sandesh K H Email:-
[email protected] Page 65
Core java
Scanner sc = new Scanner(System.in);
// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();
// Print the values to check if the input was correctly
obtained.
System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
}
}
Core java
Java String
In Java, string is basically an object that represents
sequence of char values. An array of characters works same as
Java string. For example:
char[] ch={'r','o','o','m','a','n','t','e','c','h'};
String s=new String(ch);
is same as:
String s="roomantech";
Java String class provides a lot of methods to perform
operations on string such as compare(), concat(), equals(), split(),
length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class
implements Serializable, Comparable and CharSequence
interfaces.
Core java
CharSequence Interface
The CharSequence interface is used to represent the
sequence of characters. String, StringBuffer and StringBuilder
classes implement it. It means, we can create strings in java by
using these three classes.
The Java String is immutable which means it cannot be
changed. Whenever we change any string, a new instance is
created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
What is String in java
Generally, String is a sequence of characters. But in Java,
string is an object that represents a sequence of characters. The
java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
Core java
1) String Literal
Java String literal is created by using double quotes. For
Example:
String s="welcome";
Each time you create a string literal, the JVM checks the
"string constant pool" first. If the string already exists in the
pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created.
Firstly, JVM will not find any string object with the value
"Welcome" in string constant pool, that is why it will create a new
object. After that it will find the string with the value "Welcome"
in the pool, it will not create a new object but will return the
reference to the same instance.
Core java
Note: String objects are stored in a special memory area known as
the "string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new
objects are created if it exists already in the string constant pool).
2) By new keyword
String s=new String("Welcome");//creates two objects and one ref
erence variable
In such case, JVM will create a new string object in normal
(non-pool) heap memory, and the literal "Welcome" will be placed
in the string constant pool. The variable s will refer to the object
in a heap (non-pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new
keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Sandesh K H Email:-
[email protected] Page 70
Core java
Java String class methods
The java.lang.String class provides many useful methods to
perform operations on sequence of char values.
Method Description
char charAt(int index) returns char value for the
particular index
int length() returns string length
static String format(String format, returns a formatted string.
Object... args)
static String format(Locale l, returns formatted string with
String format, Object... args) given locale.
String substring(int beginIndex) returns substring for given begin
index.
String substring(int beginIndex, returns substring for given begin
int endIndex) index and end index.
boolean contains(CharSequence s) returns true or false after
matching the sequence of char
value.
static String join(CharSequence returns a joined string.
Core java
delimiter, CharSequence...
elements)
static String join(CharSequence returns a joined string.
delimiter, Iterable<? extends
CharSequence> elements)
boolean equals(Object another) checks the equality of string
with the given object.
boolean isEmpty() checks if string is empty.
String concat(String str) concatenates the specified
string.
String replace(char old, char new) replaces all occurrences of the
specified char value.
String replace(CharSequence old, replaces all occurrences of the
CharSequence new) specified CharSequence.
static String compares another string. It
equalsIgnoreCase(String another) doesn't check case.
String[] split(String regex) returns a split string matching
regex.
String[] split(String regex, int returns a split string matching
Core java
limit) regex and limit.
String intern() returns an interned string.
int indexOf(int ch) returns the specified char value
index.
int indexOf(int ch, int fromIndex) returns the specified char value
index starting with given index.
int indexOf(String substring) returns the specified substring
index.
int indexOf(String substring, int returns the specified substring
fromIndex) index starting with given index.
String toLowerCase() returns a string in lowercase.
String toLowerCase(Locale l) returns a string in lowercase
using specified locale.
String toUpperCase() returns a string in uppercase.
String toUpperCase(Locale l) returns a string in uppercase
using specified locale.
String trim() removes beginning and ending
spaces of this string.
Core java
static String valueOf(int value) converts given type into string.
It is an overloaded method.
Do You Know?
o Why are String objects immutable?
o How to create an immutable class?
o What is string constant pool?
o What code is written by the compiler if you concatenate any
string by + (string concatenation operator)?
o What is the difference between StringBuffer and
StringBuilder class?
What will we learn in String Handling?
o Concept of String
o Immutable String
o String Comparison
o String Concatenation
o Concept of Substring
o String class methods and its usage
o StringBuffer class
o StringBuilder class
o Creating Immutable class
o toString() method
o StringTokenizer class
Immutable String in Java
In java, string objects are immutable. Immutable simply
means unmodifiable or unchangeable.
Core java
Once string object is created its data or state can't be
changed but a new string object is created.
Let's try to understand the immutability concept by the example
given below:
class TestImmutableString{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at
the end
System.out.println(s);//will print Sachin because strings are i
mmutable objects
}}
Output: Sachin
Now it can be understood by the diagram given below.
Here Sachin is not changed but a new object is created with
sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are
created but s reference variable still refers to "Sachin" not to
"Sachin Tendulkar".
Core java
But if we explicitely assign it to the reference variable, it will refer
to "Sachin Tendulkar" object.
For example:
class TestImmutableString1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
} Output: Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please
notice that still sachin object is not modified.
Why string objects are immutable in java?
Because java uses the concept of string literal. Suppose
there are 5 reference variables, all refers to one object "sachin". If
one reference variable changes the value of the object, it will be
affected to all the reference variables. That is why string objects
are immutable in java.
Java String compare
We can compare string in java on the basis of content and
reference.
It is used in authentication (by equals() method), sorting (by
compareTo() method), reference matching (by == operator) etc.
There are three ways to compare string in java:
1. By equals() method
Core java
2. By = = operator
3. By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of
the string. It compares values of string for equality. String class
provides two methods:
o public boolean equals(Object another) compares this
string to the specified object.
o public boolean equalsIgnoreCase(String
another) compares this String to another string, ignoring
case.
Example:
class TestStringComparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output:
true
true
Core java
false
Example:
class TestStringComparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
Output:
false
true
2) String compare by == operator
The = = operator compares references not values.
class TestStringComparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same
instance)
System.out.println(s1==s3);//false(because s3 refers to instanc
e created in nonpool)
}
}
Output: true
false
Sandesh K H Email:- [email protected] Page 78
Core java
3) String compare by compareTo() method
The String compareTo() method compares values
lexicographically and returns an integer value that describes if
first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class TestStringComparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Tendulkar";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//-
1(because s1<s3)
System.out.println(s3.compareTo(s1));//1(because s3 > s)
}
}
Output:0
-1
1
Core java
String Concatenation in Java
In java, string concatenation forms a new string that is the
combination of multiple strings. There are two ways to concat
string in java:
1. By + (string concatenation) operator
2. By concat() method
1) String Concatenation by + (string concatenation) operator
Java string concatenation operator (+) is used to add
strings.
For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output: Sachin Tendulkar
The Java compiler transforms above code to this:
String s=(new StringBuilder()).append("Sachin").append(" Tendul
kar).toString();
In java, String concatenation is implemented through the
StringBuilder (or StringBuffer) class and its append method.
String concatenation operator produces a new string by
appending the second operand onto the end of the first operand.
The string concatenation operator can concat not only string but
primitive values also.
Core java
For Example:
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
Output: 80Sachin4040
Note: After a string literal, all the + will be treated as string
concatenation operator.
2) String Concatenation by concat() method
The String concat() method concatenates the specified string
to the end of current string.
Syntax:
public String concat(String another)
Example:
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Core java
Substring in Java
A part of string is called substring. In other words,
substring is a subset of another string. In case of substring
startIndex is inclusive and endIndex is exclusive.
Note: Index starts from 0.
You can get substring from the given string object by one of the
two methods:
1. public String substring(int startIndex): This method
returns new String object containing the substring of the
given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int
endIndex): This method returns new String object
containing the substring of the given string from specified
startIndex to endIndex.
In case of string:
o startIndex: inclusive
o endIndex: exclusive
Let's understand the startIndex and endIndex by the code given
below.
String s="hello";
System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because
end index is exclusive).
Core java
Example of java substring
public class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
Java String class methods
The java.lang.String class provides a lot of methods to work
on string. By the help of these methods, we can perform
operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated
as a string if you submit any form in window based, web based or
mobile application.
Let's see the important methods of String class.
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into
uppercase letter and string toLowerCase() method into lowercase
letter.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
Core java
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Java String trim() method
The string trim() method eliminates white spaces before and
after string.
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
Java String startsWith() and endsWith() method
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
Java String charAt() method
The string charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Java String length() method
The string length() method returns length of the string.
String s="Sachin";
System.out.println(s.length());//6
Core java
Java String intern() method
A pool of strings, initially empty, is maintained privately by
the class String.
When the intern method is invoked, if the pool already
contains a string equal to this String object as determined by the
equals(Object) method, then the string from the pool is returned.
Otherwise, this String object is added to the pool and a reference
to this String object is returned.
String s=new String("Sachin");
String s2=s.intern();
System.out.println(s2);//Sachin
Java String valueOf() method
The string valueOf() method coverts given type such as int,
long, float, double, boolean, char and char array into string.
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Java String replace() method
The string replace() method replaces all occurrence of first
sequence of character with second sequence of character.
1. String s1="Java is a programming language. Java is a platform. J
ava is an Island.";
2. String replaceString=s1.replace("Java","J2EE");//replaces all occ
urrences of "Java" to "J2EE"
3. System.out.println(replaceString);
Core java
Java StringBuffer class
Java StringBuffer class is used to create mutable
(modifiable) string. The StringBuffer class in java is same as
String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads
cannot access it simultaneously. So it is safe and will result in an
order.
Important Constructors of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the
initial capacity of 16.
StringBuffer(String creates a string buffer with the specified
str) string.
StringBuffer(int creates an empty string buffer with the
capacity) specified capacity as length.
Core java
Important methods of StringBuffer class
Modifier and Type Method Description
public append(String s) is used to append the
synchronized specified string with this
StringBuffer string. The append() method
is overloaded like
append(char),
append(boolean),
append(int), append(float),
append(double) etc.
public insert(int offset, is used to insert the
synchronized String s) specified string with this
StringBuffer string at the specified
position. The insert()
method is overloaded like
insert(int, char), insert(int,
boolean), insert(int, int),
insert(int, float), insert(int,
double) etc.
public replace(int is used to replace the string
synchronized startIndex, int from specified startIndex
StringBuffer endIndex, String and endIndex.
str)
public delete(int is used to delete the string
Core java
synchronized startIndex, int from specified startIndex
StringBuffer endIndex) and endIndex.
public reverse() is used to reverse the string.
synchronized
StringBuffer
public int capacity() is used to return the
current capacity.
public void ensureCapacity(int is used to ensure the
minimumCapacity) capacity at least equal to
the given minimum.
public char charAt(int index) is used to return the
character at the specified
position.
public int length() is used to return the length
of the string i.e. total
number of characters.
public String substring(int is used to return the
beginIndex) substring from the specified
beginIndex.
public String substring(int is used to return the
beginIndex, int substring from the specified
endIndex) beginIndex and endIndex.
Core java
What is mutable string
A string that can be modified or changed is known as mutable
string. StringBuffer and StringBuilder classes are used for
creating mutable string.
1) StringBuffer append() method
The append() method concatenates the given argument with this
string.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the
given position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Core java
3) StringBuffer replace() method
The replace() method replaces the given string from the specified
beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from
the specified beginIndex to endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Core java
5) StringBuffer reverse() method
The reverse() method of StringBuffer class reverses the current
string.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the
current capacity of the buffer. The default capacity of the buffer
is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapac
ity*2)+2
Core java
}
}
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of StringBuffer class ensures
that the given capacity is the minimum to the current capacity. If
it is greater than the current capacity, it increases the capacity
by (oldcapacity*2)+2. For example if your current capacity is 16,
it will be (16*2)+2=34.
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapac
ity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Core java
Java StringBuilder class
Java StringBuilder class is used to create mutable
(modifiable) string. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is
available since JDK 1.5.
Important Constructors of StringBuilder class
Constructor Description
StringBuilder() creates an empty string Builder with the
initial capacity of 16.
StringBuilder(String creates a string Builder with the specified
str) string.
StringBuilder(int creates an empty string Builder with the
length) specified capacity as length.
Important methods of StringBuilder class
Method Description
public StringBuilder is used to append the specified string
append(String s) with this string. The append() method
is overloaded like append(char),
append(boolean), append(int),
append(float), append(double) etc.
public StringBuilder is used to insert the specified string
insert(int offset, String s) with this string at the specified
Core java
position. The insert() method is
overloaded like insert(int, char),
insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public StringBuilder is used to replace the string from
replace(int startIndex, specified startIndex and endIndex.
int endIndex, String str)
public StringBuilder is used to delete the string from
delete(int startIndex, int specified startIndex and endIndex.
endIndex)
public StringBuilder is used to reverse the string.
reverse()
public int capacity() is used to return the current capacity.
public void is used to ensure the capacity at least
ensureCapacity(int equal to the given minimum.
minimumCapacity)
public char charAt(int is used to return the character at the
index) specified position.
public int length() is used to return the length of the
string i.e. total number of characters.
public String is used to return the substring from the
substring(int specified beginIndex.
beginIndex)
Core java
public String is used to return the substring from the
substring(int specified beginIndex and endIndex.
beginIndex, int
endIndex)
Java StringBuilder Examples
Let's see the examples of different methods of StringBuilder
class.
1) StringBuilder append() method
The StringBuilder append() method concatenates the given
argument with this string.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string
with this string at the given position.
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
Sandesh K H Email:-
[email protected] Page 95
Core java
}
}
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string
from the specified beginIndex and endIndex.
class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string
from the specified beginIndex to endIndex.
class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Core java
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the
current string.
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the
current capacity of the Builder. The default capacity of the
Builder is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBuilderExample6{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapac
ity*2)+2
}
}
Core java
7) StringBuilder ensureCapacity() method
The ensureCapacity() method of StringBuilder class ensures
that the given capacity is the minimum to the current capacity. If
it is greater than the current capacity, it increases the capacity
by (oldcapacity*2)+2. For example if your current capacity is 16,
it will be (16*2)+2=34.
class StringBuilderExample7{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapac
ity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Core java
Difference between String and StringBuffer
There are many differences between String and
StringBuffer. A list of differences between String and StringBuffer
are given below:
No. String StringBuffer
1) String class is immutable. StringBuffer class is
mutable.
2) String is slow and consumes StringBuffer is fast and
more memory when you concat consumes less memory
too many strings because every when you cancat
time it creates new instance. strings.
3) String class overrides the StringBuffer class
equals() method of Object class. doesn't override the
So you can compare the contents equals() method of
of two strings by equals() Object class.
method.
Core java
Performance Test of String and StringBuffer
public class ConcatTest{
public static String concatWithString() {
String t = "Java";
for (int i=0; i<10000; i++){
t = t + "J2EE";
}
return t;
}
public static String concatWithStringBuffer(){
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("J2EE");
}
return sb.toString();
}
public static void main(String[] args){
long startTime = System.currentTimeMillis();
concatWithString();
System.out.println("Time taken by Concating with String: "
+(System.currentTimeMillis()-startTime)+"ms");
startTime = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("Time taken by Concating with StringB
uffer: "+(System.currentTimeMillis()-startTime)+"ms");
}
}
Core java
Time taken by Concating with String: 578ms
Time taken by Concating with StringBuffer: 0ms
String and StringBuffer HashCode Test
As you can see in the program given below, String returns
new hashcode value when you concat string but StringBuffer
returns same.
public class InstanceTest{
public static void main(String args[]){
System.out.println("Hashcode test of String:");
String str="java";
System.out.println(str.hashCode());
str=str+"J2EE";
System.out.println(str.hashCode());
System.out.println("Hashcode test of StringBuffer:");
StringBuffer sb=new StringBuffer("java");
System.out.println(sb.hashCode());
sb.append("J2EE");
System.out.println(sb.hashCode());
}
}
Hashcode test of String:
3254818
-582078230
Hashcode test of StringBuffer:
617901222
617901222
Sandesh K H Email:-
[email protected] Page 101
Core java
Difference between StringBuffer and StringBuilder
Java provides three classes to represent a sequence of
characters: String, StringBuffer, and StringBuilder. The String
class is an immutable class whereas StringBuffer and
StringBuilder classes are mutable. There are many differences
between StringBuffer and StringBuilder. The StringBuilder class
is introduced since JDK 1.5.
A list of differences between StringBuffer and StringBuilder are
given below:
No. StringBuffer StringBuilder
1) StringBuffer StringBuilder is non-
is synchronized i.e. thread synchronized i.e. not
safe. It means two threads thread safe. It means two
can't call the methods of threads can call the
StringBuffer methods of StringBuilder
simultaneously. simultaneously.
2) StringBuffer is less StringBuilder is more
efficient than StringBuilder. efficient than StringBuffer.
Core java
StringBuffer Example
//Java Program to demonstrate the use of StringBuffer class.
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}
hellojava
StringBuilder Example
//Java Program to demonstrate the use of StringBuilder class.
public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("java");
System.out.println(builder);
}
}
hellojava
Core java
Performance Test of StringBuffer and StringBuilder
Let's see the code to check the performance of StringBuffer
and StringBuilder classes.
//Java Program to demonstrate the performance of StringBuffer
and StringBuilder classes.
public class ConcatTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("J2EE");
}
System.out.println("Time taken by StringBuffer: " + (System
.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
sb2.append("J2EE");
}
System.out.println("Time taken by StringBuilder: " + (Syste
m.currentTimeMillis() - startTime) + "ms");
}
}
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms
Core java
How to create Immutable class?
There are many immutable classes like String, Boolean,
Byte, Short, Integer, Long, Float, Double etc. In short, all the
wrapper classes and String class is immutable. We can also
create immutable class by creating final class that have final data
members as the example given below:
Example to create Immutable class
In this example, we have created a final class named
Employee. It have one final datamember, a parameterized
constructor and getter method.
public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber)
{
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}
Core java
The above class is immutable because:
o The instance variable of the class is final i.e. we cannot
change the value of it after creating an object.
o The class is final so we cannot create the subclass.
o There is no setter methods i.e. we have no option to change
the value of the instance variable.
These points makes this class as immutable.
Java toString() method
If you want to represent any object as a string, toString()
method comes into existence.
The toString() method returns the string representation of the
object.
If you print any object, java compiler internally invokes the
toString() method on the object. So overriding the toString()
method, returns the desired output, it can be the state of an
object etc. depends on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we
can return values of the object, so we don't need to write much
code.
Understanding problem without toString() method
Let's see the simple code that prints reference.
class Student{
int rollno;
String name;
Core java
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Roo","davangere");
Student s2=new Student(102,"Pmkk","davangere");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2
prints the hashcode values of the objects but I want to print the
values of these objects. Since java compiler internally calls
toString() method, overriding this method will return the specified
values. Let's understand it with the example given below:
Example of Java toString() method
Now let's see the real example of toString() method.
class Student{
int rollno;
String name;
String city;
Core java
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){
//overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Roo","davangere");
Student s2=new Student(102,"Pmkk","davangere");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:101 Roo davangere
102 Pmkk davangere
Core java
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a
string into tokens. It is simple way to break string.
It doesn't provide the facility to differentiate numbers,
quoted strings, identifiers etc. like StreamTokenizer class. We will
discuss about the StreamTokenizer class in I/O chapter.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.
Constructor Description
StringTokenizer(String str) creates StringTokenizer with
specified string.
StringTokenizer(String str, creates StringTokenizer with
String delim) specified string and delimeter.
StringTokenizer(String str, creates StringTokenizer with
String delim, boolean specified string, delimeter and
returnValue) returnValue. If return value is true,
delimiter characters are considered
to be tokens. If it is false, delimiter
characters serve to separate
tokens.
Core java
Methods of StringTokenizer class
The 6 useful methods of StringTokenizer class are as follows:
Public method Description
boolean hasMoreTokens() checks if there is more tokens
available.
String nextToken() returns the next token from the
StringTokenizer object.
String nextToken(String returns the next token based on the
delim) delimeter.
boolean same as hasMoreTokens() method.
hasMoreElements()
Object nextElement() same as nextToken() but its return type
is Object.
int countTokens() returns the total number of tokens.
Core java
Simple example of StringTokenizer class
Let's see the simple example of StringTokenizer class that
tokenizes a string "my name is Davangere" on the basis of
whitespace.
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is Davang
ere"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:my
name
is
Davangere
Example of nextToken(String delim) method of
StringTokenizer class
import java.util.*;
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,Dava
ngere");
Sandesh K H Email:-
[email protected] Page 111
Core java
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}
Output:Next token is : my
StringTokenizer class is deprecated now. It is recommended to use
split() method of String class or regex (Regular Expression).
Core java
Java OOPs Concepts
we will learn about the basics of OOPs. Object-Oriented
Programming is a paradigm that provides many concepts, such
as inheritance, data binding, polymorphism, etc.
The popular object-oriented languages
are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to
implement real-world entities, for example, object, classes,
abstraction, inheritance, polymorphism, etc.
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair,
table, computer, watch, etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by
providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Core java
Apart from these concepts, there are some other terms which are
used in Object-Oriented
Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
Email:- Page 114
Core java
Object
Any entity that has state and behavior is known as an
object. For example, a chair, pen, table, keyboard, bike, etc. It
can be physical or logical.
An Object can be defined as an instance of a class. An
object contains an address and takes up some space in memory.
Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of
message accepted and the type of response returned by the
objects.
Example: A dog is an object because it has states like color,
name, breed, etc. as well as behaviors like wagging the tail,
barking, eating, etc.
Email:- Page 115
Core java
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you
can create an individual object. Class doesn't consume any
space.
Inheritance
When one object acquires all the properties and behaviours of
a parent object, it is known as inheritance. It provides code
reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as
polymorphism. For example: to convince the customer differently,
to draw something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to
achieve polymorphism.
Another example can be to speak something; for example, a cat
speaks meow, dog barks woof, etc.
Core java
Abstraction
Hiding internal details and showing functionality is known
as abstraction. For example phone call, we don't know the
internal processing.
In Java, we use abstract class and interface to achieve
abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single
encapsulation. For example, a capsule, it is
unit are known as encapsulation.
wrapped with different medicines.
A java class is the example of encapsulation. Java bean is
the fully encapsulated class because all the data members are
private here.
Coupling
Coupling refers to the knowledge or information or
dependency of another class. It arises when classes are aware of
each other. If a class has the details information of another class,
there is strong coupling.
In Java, we use private, protected, and public
public modifiers to
display the visibility level of a class, method, and field. You can
use interfaces for the weaker coupling because there is no
concrete implementation.
Email:- Page 117
Core java
Cohesion
Cohesion refers to the level of a component which performs
a single well-defined task. A single well-defined task is done by a
highly cohesive method. The weakly cohesive method will split
the task into separate parts. The java.io package is a highly
cohesive package because it has I/O related classes and
interface. However, the java.util package is a weakly cohesive
package because it has unrelated classes and interfaces.
Association
Association represents the relationship between the objects.
Here, one object can be associated with one object or many
objects. There can be four types of association between the
objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
Let's understand the relationship with real-time examples. For
example, One country can have one prime minister (one to one),
and a prime minister can have many ministers (one to many).
Also, many MP's can have one prime minister (many to one), and
many ministers can have many departments (many to many).
Association can be undirectional or bidirectional.
Core java
Aggregation
Aggregation is a way to achieve Association. Aggregation
represents the relationship where one object contains other
objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java.
Like, inheritance represents the is-a relationship. It is another
way to reuse objects.
Composition
The composition is also a way to achieve Association. The
composition represents the relationship where one object
contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent
object. It is the state where containing objects do not have an
independent existence. If you delete the parent object, all the
child objects will be deleted automatically.
Advantage of OOPs over Procedure-oriented programming
language
1) OOPs makes development and maintenance easier, whereas,
in a procedure-oriented programming language, it is not easy to
manage if code grows as project size increases.
2) OOPs provides data hiding, whereas, in a procedure-oriented
programming language, global data can be accessed from
anywhere.
Core java
Figure: Data Representation in Procedure-Oriented
Procedure Oriented Programming
Figure: Data Representation in Object-Oriented
Object Oriented Programming
3) OOPs provides the ability to simulate real-world
real world event much
more effectively. We can provide the solution of real word problem
if we are using the Object-Oriented
Object Oriented Programming language.
Email:- Page 120
Core java
Java Naming conventions
Java naming convention is a rule to follow as you decide
what to name your identifiers such as class, package, variable,
constant, method, etc.
But, it is not forced to follow. So, it is known as convention not
rule. These conventions are suggested by several Java
communities such as Sun Microsystems and Netscape.
All the classes, interfaces, packages, methods and fields of
Java programming language are given according to the Java
naming convention. If you fail to follow these conventions, it may
generate confusion or erroneous code.
Advantage of naming conventions in java
By using standard Java naming conventions, you make
your code easier to read for yourself and other programmers.
Readability of Java program is very important. It indicates that
less time is spent to figure out what the code does.
The following are the key rules that must be followed by every
identifier:
o The name must not contain any white spaces.
o The name should not start with special characters like &
(ampersand), $ (dollar), _ (underscore).
Let's see some other rules that should be followed by identifiers.
Core java
Class
o It should start with the uppercase letter.
o It should be a noun such as Color, Button, System, Thread,
etc.
o Use appropriate words, instead of acronyms.
Example: -
public class Employee
{
//code snippet
}
Interface
o It should start with the uppercase letter.
o It should be an adjective such as Runnable, Remote,
ActionListener.
o Use appropriate words, instead of acronyms.
Example: -
interface Printable
{
//code snippet
}
Core java
Method
o It should start with lowercase letter.
o It should be a verb such as main(), print(), println().
o If the name contains multiple words, start it with a
lowercase letter followed by an uppercase letter such as
actionPerformed().
Example:-
class Employee
{
//method
void draw()
{
//code snippet
}
}
Variable
o It should start with a lowercase letter such as id, name.
o It should not start with the special characters like &
(ampersand), $ (dollar), _ (underscore).
o If the name contains multiple words, start it with the
lowercase letter followed by an uppercase letter such as
firstName, lastName.
o Avoid using one-character variables such as x, y, z.
Core java
Example :-
class Employee
{
//variable
int id;
//code snippet
}
Package
o It should be a lowercase letter such as java, lang.
o If the name contains multiple words, it should be separated
by dots (.) such as java.util, java.lang.
Example :-
package com.javaJ2EE; //package
class Employee
{
//code snippet
}
Core java
Constant
o It should be in uppercase letters such as RED, YELLOW.
o If the name contains multiple words, it should be separated
by an underscore(_) such as MAX_PRIORITY.
o It may contain digits but not as the first letter.
Example :-
class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}
Core java
Objects and Classes in Java
An object in Java is the physical as well as a logical entity,
whereas, a class in Java is a logical entity only.
What is an object in Java
An entity that has state and behavior is known as an object
e.g., chair, bike, marker, pen, table, car, etc. It can be physical or
logical (tangible and intangible). The example of an intangible
object is the banking system.
An object has three characteristics:
o State: represents the data (value) of an object.
o Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external
user. However, it is used internally by the JVM to identify
each object uniquely.
Core java
For Example, Pen is an object. Its name is Reynolds; color is
white, known as its state. It is used to write, so writing is its
behavior.
An object is an instance of a class. A class is a template or
blueprint from which objects are created. So, an object is the
instance(result) of a class.
Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
Core java
What is a class in Java
A class is a group of objects which have common properties.
It is a template or blueprint from which objects are created. It is a
logical entity. It can't be physical.
A class in Java can contain:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Core java
Syntax to declare a class:
class <class_name>{
field;
method;
}
Instance variable in Java
A variable which is created inside the class but outside the
method is known as an instance variable. Instance variable
doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created. That is why it is known as
an instance variable.
Method in Java
In Java, a method is like a function which is used to expose
the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
new keyword in Java
The new keyword is used to allocate memory at runtime. All
objects get memory in Heap memory area.
Core java
Object and Class Example: main within the class
In this example, we have created a Student class which has
two data members id and name. We are creating the object of the
Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
File: Student.java
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student //
Printing values of the object
System.out.println(s1.id);//accessing member through referenc
e variable
System.out.println(s1.name);
}
}
Object and Class Example: main outside the class
In real time development, we create classes and use it from
another class. It is a better approach than previous one. Let's see
a simple example, where we are having main() method in another
class.
Core java
We can have multiple classes in different Java files or single
Java file. If you define multiple classes in a single Java source
file, it is a good idea to save the file name with the class name
which has main() method.
File: TestStudent1.java
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main
method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Core java
3 Ways to initialize object
There are 3 ways to initialize object in Java.
1. By reference variable
2. By method
3. By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object.
Let's see a simple example where we are going to initialize the
object through a reference variable.
File: TestStudent2.java
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Rooman";
System.out.println(s1.id+" "+s1.name);//printing members with
a white space
}
}
Core java
We can also create multiple objects and store information in
it through reference variable.
File: TestStudent3.java
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Rooman";
s2.id=102;
s2.name="Technology";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Core java
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student
class and initializing the value to these objects by invoking the
insertRecord method. Here, we are displaying the state (data) of
the objects by invoking the displayInformation() method.
File: TestStudent4.java
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Core java
As you can see in the above figure, object gets the memory
in heap memory area. The reference variable refers to the object
allocated in the heap memory area. Here, s1 and s2 both are
reference variables that refer to the objects allocated in memory
3) Object and Class Example: Initialization through a
constructor
We will learn about constructors in Java later.
Object and Class Example: Employee
Let's see an example where we are maintaining records of
employees.
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
Sandesh K H Email: [email protected]
Email:- Page 135
Core java
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"aaaaa",45000);
e2.insert(102,"bbbbb",25000);
e3.insert(103,"ccccc",55000);
e1.display();
e2.display();
e3.display();
}
}
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
Core java
Anonymous object
Anonymous simply means nameless. An object which has
no reference is known as an anonymous object. It can be used at
the time of object creation only.
If you have to use an object only once, an anonymous object is a
good approach. For example:
new Calculation();//anonymous object
Calling method through a reference:
Calculation c=new Calculation();
c.fact(5);
Calling method through an anonymous object
new Calculation().fact(5);
Let's see the full example of an anonymous object in Java.
Core java
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous obje
ct
}
}
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case
of primitives.
Initialization of primitive variables:
int a=10, b=20;
Initialization of refernce variables:
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two
objects
Let's see the example:
//Java Program to illustrate the use of Rectangle class which
//has length and width data members
class Rectangle{
Core java
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating tw
o objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Real World Example: Account
File: TestAccount.java
//Java Program to demonstrate the working of a banking-
system
//where we deposit and withdraw amount from our account.
//Creating an Account class which has deposit() and withdraw()
methods
class Account{
int acc_no;
Sandesh K H Email:-
[email protected] Page 139
Core java
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
//deposit method
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
//withdraw method
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
Core java
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Aaaaa",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}
Constructors in Java
In Java, a constructor is a block of codes similar to the
method. It is called when an instance of the class is created. At
the time of calling constructor, memory for the object is allocated
in the memory.
It is a special type of method which is used to initialize the
object.
Every time an object is created using the new() keyword, at
least one constructor is called.
It calls a default constructor if there is no constructor
available in the class. In such case, Java compiler provides a
default constructor by default.
Core java
There are two types of constructors in Java: no-arg
constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at
the time of object creation. It is not necessary to write a
constructor for a class. It is because java compiler creates a
default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and
synchronized
Note: We can use access modifiers while declaring a constructor. It
controls the object creation. In other words, we can have private,
protected, public or default constructor in Java.
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Core java
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have
any parameter.
Syntax of default constructor:
<class_name>( )
{
}
Example of default constructor
In this example, we are creating the no-arg
arg constructor in the
Bike class. It will be invoked at the time of object creation
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1( )
{
System.out.println("Bike
"Bike is created");
}
//main method
Email:- Page 143
Core java
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Rule: If there is no constructor in a class, compiler automatically
creates a default constructor.
Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to
the object like 0, null, etc., depending on the type.
Example of default constructor that displays the default
values
//Let us see another example of default constructor
//which displays the default values
class Student3
{
int id;
String name;
Email:- Page 144
Core java
//method to display the value of id and name
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Explanation:
In the above class,you are not creating any constructor so
compiler provides you a default constructor. Here 0 and null
values are provided by default constructor.
Java Parameterized Constructor
A constructor which has a specific number of parameters is
called a parameterized constructor.
Core java
Why use the parameterized constructor?
The parameterized constructor is used to provide different
values to distinct objects. However, you can provide the same
values also.
Example of parameterized constructor
In this example, we have created the constructor of Student
class that have two parameters. We can have any number of
parameters in the constructor.
//Java Program to demonstrate the use of the parameterized con
structor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Java");
Student4 s2 = new Student4(222,"J2EE");
//calling method to display the values of object
s1.display();
Sandesh K H Email:-
[email protected] Page 146
Core java
s2.display();
}
}
Constructor Overloading in Java
In Java, a constructor is just like a method but without
return type. It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having
more than one constructor with different parameter lists. They
are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of
parameters in the list and their types.
Example of Constructor Overloading
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
Sandesh K H Email:-
[email protected] Page 147
Core java
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Java");
Student5 s2 = new Student5(222,"J2EE",25);
s1.display();
s2.display();
}
}
Difference between constructor and method in Java
There are many differences between constructors and
methods. They are given below.
Java Constructor Java Method
A constructor is used to initialize the A method is used to
state of an object. expose the behavior of an
object.
A constructor must not have a A method must have a
return type. return type.
Core java
The constructor is invoked implicitly. The method is invoked
explicitly.
The Java compiler provides a default The method is not
constructor if you don't have any provided by the compiler
constructor in a class. in any case.
The constructor name must be same The method name may or
as the class name. may not be same as the
class name.
Q) Does constructor return any value?
Yes, it is the current class instance (You cannot use return type
yet it returns a value).
Core java
Can constructor perform other tasks instead of
initialization?
Yes, like object creation, starting a thread, calling a method, etc.
You can perform any operation in the constructor as you perform
in the method.
Is there Constructor class in Java?
Yes.
What is the purpose of Constructor class?
Java provides a Constructor class which can be used to get
the internal information of a constructor in the class. It is found
in the java.lang.reflect package.
Java static keyword
The static keyword in Java is used for memory
management mainly. We can apply java static keyword with
variables, methods, blocks and nested class. The static keyword
belongs to the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
1) Java static variable
If you declare any variable as static, it is known as a static
variable.
Core java
o The static variable can be used to refer to the common
property of all objects (which is not unique for each object),
for example, the company name of employees, college name
of students, etc.
o The static variable gets memory only once in the class area
at the time of class loading.
Advantages of static
atic variable
It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS"
"ITS";
}
Suppose there are 500 students in my college, now all
instance data members will get memory each time when the
object is created. All students have its unique rollno and name,
so instance data member is good in such case. Here, "college"
refers to the common property of all objects. If we make
mak it static,
this field will get the memory only once.
Sandesh K H Email:
[email protected] Email:- Page 151
Core java
Java static property is shared to all objects.
Example of static variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of co
de
//Student.college="PMKK";
s1.display();
s2.display();
Core java
}
}
Restrictions for the static method
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or
call non-static method directly.
2. this and super cannot be used in static context.
Q) Why is the Java main method static?
Ans) It is because the object is not required to call a static
method. If it were a non-static method, JVM creates an object
first then call main() method that will lead the problem of extra
memory allocation.
3) Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of
classloading.
Example of static block
class A2{
static{System.out.println("static block is invoked");}
Core java
public static void main(String args[]){
System.out.println("Hello main");
}
}
this keyword in java
There can be a lot of usage of java this keyword. In java, this is
a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from
the method.
Core java
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables and
parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the
example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
Core java
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and
instance variables are same. So, we are using this keyword to
distinguish local variable and instance variable.
Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
Core java
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
2) this: to invoke current class method
You may invoke the method of the current class by using
the this keyword. If you don't use the this keyword, compiler
automatically adds this keyword while invoking the method. Let's
see the example
class A{
void m(){
System.out.println("hello m");
}
void n(){
System.out.println("hello n");
Core java
//m();//same as this.m()
this.m();
} }
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current
class constructor. It is used to reuse the constructor. In other
words, it is used for constructor chaining.
Calling default constructor from parameterized constructor:
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Calling parameterized constructor from default constructor:
class A{
A(){
Core java
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Real usage of this() constructor call
The this() constructor call should be used to reuse the
constructor from the constructor. It maintains the chain between
the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this
keyword.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
Core java
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+
fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
Rule: Call to this() must be the first statement in constructor.
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the
method. It is mainly used in the event handling. Let's see the
example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
Core java
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
5) this: to pass as argument in the constructor call
We can pass the this keyword in the constructor also. It is
useful if we have to use one object in multiple classes. Let's see
the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
Core java
6) this keyword can be used to return current class instance
We can return this keyword as an statement from the
method. In such case, return type of the method must be the
class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
Example of this keyword that you return as a statement from
the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}