Core_Java
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.
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
class class_name
{
public static void main(String[ ] args)
{
//statement or code to execute
}
}
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
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'
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>
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....
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;
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';
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);
}
}
Output :
E:\Core_Java>javac Program.java
E:\Core_Java>java Program
21
5.5
12345.0
1234
a
E:\Core_Java>
Example :
class Program
{
public static void main(String[] args)
{
final int pin=1234;
pin=4321;
System.out.println(pin);
}
}
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
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
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
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));
}
}
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>
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
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));
}
}
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
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 );
}
}
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--)
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>
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
}
}
}
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
}
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.
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;
}
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");
}
}}
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
}
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);
}//end of i
}//end of j
}
}
Pyramid Example
Output:
*
**
***
****
*****
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
.
.
.
ctrl+c
Syntax:
while(condition)
{
//code to be executed
}
Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Syntax:
do{
//code to be executed
}while(condition);
Example:
Syntax:
jump-statement;
break;
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
Output:
1
2
3
4
6
7
8
9
10
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
Syntax:
/*
This
is
multi line
comment
*/
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.
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
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!");
}
Example
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
Example
Multiple Parameters
Example
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;
}
Example
return x + y;
System.out.println(z);
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.
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
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]);
}
}
ArrayIndexOutOfBoundsException
Output:
Example
In our example, we will use the nextLine() method, which is used
to read Strings:
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a
Scanner object
System.out.println("Enter username");
Input Types
Method Description
Example
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";
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.
1. By string literal
2. By new keyword
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
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).
Method Description
delimiter, CharSequence...
elements)
int indexOf(int ch, int fromIndex) returns the specified char value
index starting with given index.
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?
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".
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.
1. By equals() method
2. By = = operator
3. By compareTo() method
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
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
s1 == s2 :0
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
For Example:
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
Output: 80Sachin4040
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
}
}
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.
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
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Constructor Description
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
}
}
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
}
}
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
}
}
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
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
}
}
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
}
}
Constructor Description
Method Description
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
}
}
}
}
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
StringBuffer Example
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
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:
class Student{
int rollno;
String name;
String city;
StringTokenizer in Java
Constructor Description
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
Output:Next token is : my
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
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.
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
Polymorphism
Abstraction
Hiding internal details and showing functionality is known
as abstraction. For example phone call, we don't know the
internal processing.
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.
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.
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
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.
The following are the key rules that must be followed by every
identifier:
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: -
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
}
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.
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 :-
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
}
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.
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
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.
File: TestStudent1.java
1. By reference variable
2. By method
3. By constructor
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
}
}
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);
}
}
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();
}
}
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
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();
}
}
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
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.
new Calculation().fact(5);
Let's see the full example of an anonymous object in 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
}
}
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();
}
}
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);}
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.
s2.display();
}
}
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
}
}
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.
}
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{
class A{
void m(){
System.out.println("hello m");
}
void n(){
System.out.println("hello n");
//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(){
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();
}}
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();
}}