Java
Java
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995.
James Gosling is known as the father of Java. Before Java, its name was Oak.
Since Oak was already a registered company, so James Gosling and his team changed the
name from Oak to Java.
The team initiated this project to develop a language for digital devices such as set-top
boxes, television, etc.
Originally C++ was considered to be used in the project but the idea was rejected for
several reasons(For instance C++ required more memory).
Gosling endeavoured to alter and expand C++ however before long surrendered that
for making another stage called Green.
James Gosling and his team called their project “Greentalk” and its file extension
was .gt and later became to known as “OAK”. Why “Oak”? The name Oak was used
by Gosling after an oak tree that remained outside his office.
Features of Java
Siddhant College Of Engineering
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
Siddhant College Of Engineering
6. Encapsulation
C++ vs Java
Mainly used for C++ is mainly used for Java is mainly used for application
system programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile applications.
Design Goal C++ was designed for Java was designed and created as
systems and applications an interpreter for printing systems
programming. It was an but later extended as a support
extension of the C network computing. It was
programming language designed to be easy to use and
accessible to a broader audience.
.
Goto C++ supports the goto Java doesn't support the goto
statement.
statement.
in java.
Compiler and C++ uses compiler only. C+ Java uses both compiler and
Interpreter + is compiled and run using interpreter. Java source code is
the compiler which converts converted into bytecode at
source code into machine compilation time. The interpreter
code so, C++ is platform executes this bytecode at runtime
dependent. and produces output. Java is
interpreted that is why it is
platform-independent.
Call by Value C++ supports both call by Java supports call by value only.
and Call by value and call by reference. There is no call by reference in
reference java.
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread
support for threads. It relies
support.
on third-party libraries for
thread support.
unsigned right C++ doesn't support >>> Java supports unsigned right shift
shift >>> operator. >>> operator that fills zero at the
top for the negative numbers. For
positive numbers, it works same
like >> operator.
Inheritance Tree C++ always creates a new Java always uses a single
inheritance tree. inheritance tree because all classes
Siddhant College Of Engineering
Class
1. Class is a set of object which shares common characteristics/ behavior and common
properties/ attributes.
2. Class is not a real world entity. It is just a template or blueprint or prototype from
which objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and group of methods.
classStudent
{
intid;//data member (also instance variable)
String name; //data member (also instance variable)
publicstaticvoidmain(String args[])
{
Student s1=newStudent();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Java provides a reserved keyword class to define a class. The keyword must be followed by
the class name. Inside the class, we declare methods and variables.
Syntax:
1. <access specifier> class class_name
2. {
3. // member variables
4. // class methods
5. }
Siddhant College Of Engineering
Instance variables and methods are accessed via objects with the help of a dot (.) operator.
The dot operator creates a link between the name of the instance variable and the name of the
class with which it is used.
class Employee
{
String name;
int age;
float bsal, gsal;
Object
It is a basic unit of Object-Oriented Programming and represents real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An
object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior: It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Example of an object: dog
There is various way to create an object in Java that we will discuss in this section, and also
learn how to create an object in Java.
Using the new keyword is the most popular way to create an object or instance of the class.
When we create an instance of the class by using the new keyword, it allocates memory
(heap) for the newly created object and also returns the reference of that object to that
memory. The new keyword is also used to create an array.
Method in Java
a method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task.
It provides the reusability of code. We can also easily modify code using methods.
Types of Method
o Predefined Method
o User-defined Method
Siddhant College Of Engineering
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.
Siddhant College Of Engineering
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
The Java compiler breaks the line of code into text (words) is called Java tokens.
It is useful for compilers to detect errors. Remember that the delimiters are not part of the
Java tokens.
In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [, ], ),
System, ., out, println, javatpoint, etc. are the Java tokens.
o Keywords
o Identifiers
Identifiers are used to name a variable, constant, function, class, and array.
The label is also known as a special kind of identifier that is used in the goto statement.
Remember that the identifier name must be different from the reserved keywords. There are
some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
o Literals
is defined by the programmer. Once it has been defined cannot be changed. Java provides
five types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
o Operators
In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
o Separators
The separators in Java is also known as punctuators. There are nine separators in
Java, are as follows:
separator <= ; | , | . | ( | ) | { | } | [ | ]
o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
Siddhant College Of Engineering
o Comments
Comments allow us to specify information about the program inside our Java code.
Java compiler recognizes these comments as tokens but excludes it form further processing.
The Java compiler treats comments as whitespaces. Java provides the following two types of
comments:
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Dynamic initialization of object refers to initializing the objects at run time i.e. the initial
value of an object is to be provided during run time.
Siddhant College Of Engineering
Dynamic initialization can be achieved using constructors and passing parameters values to
the constructors.
This type of initialization is required to initialize the class variables during run time.
If any variable is not assigned with value at compile-time and assigned at run time is
called dynamic initialization of a variable.
publicclass Main {
publicstaticvoidmain(String args[]) {
// c is dynamically initialized
double c = Math.sqrt(2 * 2);
In programming, a variable can be declared and defined inside a class, method, or block. It
defines the scope of the variable i.e. the visibility or accessibility of a variable. Variable
declared inside a block or method are not visible to outside. If we try to do so, we will get a
compilation error. Note that the scope of a variable can be nested.
o We can declare variables anywhere in the program but it has limited scope.
o A variable can be a parameter of a method or constructor.
o A variable can be defined and declared inside the body of a method and constructor.
o It can also be defined inside blocks and loops.
o Variable declared inside main() function cannot be accessed outside the main()
function
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Constants can be declared using Java's static and final keywords. The static keyword is used
for memory management and final keyword signifies the property that the value of the
variable cannot be changed. It makes the primitive data types immutable.
Types of Constants
1. Numeric Constants
o Integer Constants
o Real Constants
2. Non-numeric Constants
o Character Constants
o String Constants
Example:
staticfinalfloat PI = 3.14f;
Siddhant College Of Engineering
symbolic names take the some form as variable names. But they one written in capitals
to distance from variable names. This is only convention not a rule.
After declaration of symbolic constants they shouldn’t be assigned any other value with
in the program by using an assignment statement.
When you assign a value of one data type to another, the two types might not be compatible
with each other.
If the data types are compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion, and if not then they need to be cast or converted
explicitly.
Datatyp
e Bits Acquired In Memory
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)
double 64 (8 bytes)
// Main class
class GFG {
// Main class
public class GFG {
// Main class
class GFG {
// The Expression
double result = (f * b) + (i / c) - (d * s);
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
Arithmetic Operators
These operators involve the mathematical operators that can be used to perform various
simple or advanced arithmetic operations on the primitive data types referred to as the
operands.
class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
Siddhant College Of Engineering
Relational operators are used to check the relationship between two operands.
The return value of a comparison is either true or false. These values are known as Boolean
values.
For example,
class Main {
public static void main(String[] args) {
Siddhant College Of Engineering
// create variables
int a = 7, b = 11;
// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
Siddhant College Of Engineering
import java.io.*;
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 20, d = 0;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
Example 2
class Logicaloperator {
public static void main(String[] args) {
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Siddhant College Of Engineering
Operator Meaning
Unary plus: not necessary to use since numbers are positive without
+
using it
class unary {
public static void main(String[] args) {
// declare variables
int a = 12, b = 12;
int result1, result2;
// original value
System.out.println("Value of a: " + a);
// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
Siddhant College Of Engineering
// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
Example 2
// Java Program to Illustrate Unary NOT Operator
// Importing required classes
import java.io.*;
// Main class
class GFG {
For example,
~ 00100011
________
11011100 =220 (In decimal)
Here, ~ is a bitwise operator. It inverts the value of each bit (0 to 1 and 1 to 0).
Operator Description
~ Bitwise Complement
^ Bitwise exclusive OR
publicclassbitwiseop {
publicstaticvoidmain(String[] args) {
//Variables Definition and Initialization
Siddhant College Of Engineering
//Bitwise AND
System.out.println("num1 & num2 = "+ (num1 & num2));
//Bitwise OR
System.out.println("num1 | num2 = "+ (num1 | num2) );
//Bitwise XOR
System.out.println("num1 ^ num2 = "+ (num1 ^ num2) );
}
}
class Main {
public static void main(String[] args) {
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Java Mathematical Functions
Java Mathematical functions are predefined functions which accept values and return the
result. To use mathematical functions, we have to use Math class in our program.
With the help of mathematical functions we can easily solve a complex equation in our
program, for example, if we want to find the square root of a number, then we can
use sqrt() mathematical function to find the square root of a given number.
pow() Function
sqrt() Function
The sqrt() function returns the square root of a positive number. Remember that square root
of a negative can not be calculated.
Syntax of sqrt() function
doublesqrt(doublenum);
max() Function
The max() function returns the greater among two numbers. The number can be
an integer, long, float or double value.
min() Function
The min() function returns the smallest among two numbers. The number can be
an integer, long, float or double value.
Syntax of min() function
intmin(int a,int b);
abs() Function
The abs() function returns the absolute value of a number. The number can be
an integer, long, float or double value. Here Absolute value means number without negative
sign. The absolute value of a number is always positive.
Syntax of abs() function
intabs(intnum);
Siddhant College Of Engineering
The Java Math exp() method returns the Euler's number e raised to the power of the specified
value.
The round() method rounds the specified value to the closest int or long value and returns it.
Math.round(value)
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax
if(condition){
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
6. }
7. else{
8. System.out.println("COMMON YEAR");
9. }
10. }
11. }
Practice Example :
public class time{
public static void main(String args[]){
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
nested-if
Nested if statements mean an if statement inside an if statement. Yes, java allows us to nest
if statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
Siddhant College Of Engineering
}
// Java program to illustrate nested-if statement
import java.util.*;
class NestedIfDemo {
public static void main(String args[])
{
int i = 10;
if (i == 10 || i<15) {
// First if statement
if (i< 15)
System.out.println("i is smaller than 15");
Siddhant College Of Engineering
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i< 12)
System.out.println(
"i is smaller than 12 too");
} else{
System.out.println("i is greater than 15");
}
}
}
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Instead of writing many if..else statements, you can use the switch statement.
Syntax
switch(expression){
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}
Siddhant College Of Engineering
Nested-Switch Statement:
Nested-Switch statements refers to Switch statements inside of another Switch Statements.
case 2:
System.out.println("Total semesters passed: 2");
break;
}
break;
case 2:
switch (semester) {
case 1:
System.out.println("Total semesters passed: 3");
break;
case 2:
System.out.println("Total semesters passed: 4");
break;
}
break;
case 3:
switch (semester) {
case 1:
System.out.println("Total semesters passed: 5");
break;
case 2:
System.out.println("Total semesters passed: 6");
break;
}
break;
case 4:
switch (semester) {
case 1:
System.out.println("Total semesters passed: 7");
break;
Siddhant College Of Engineering
case 2:
System.out.println("Total semesters passed: 8");
break;
}
break;
}
}
}
The Java while loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not
fixed, it is recommended to use the while loop.
Syntax:
1. while (condition){
2. //code to be executed
3. Increment / decrement statement
4. }
1. The initialExpression initializes and/or declares variables and executes only once.
2. The condition is evaluated. If the condition is true, the body of the for loop is executed.
3. The updateExpression updates the value of initialExpression.
4. The condition is evaluated again. The process continues until the condition is false.
Siddhant College Of Engineering
Classforloop {
publicstaticvoidmain(String[] args)
{
for(inti = 1; i<= 10; i++) {
System.out.println(i);
}
}
}
It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Syntax:
for (type var : array)
{
statements using var;
}
{
public static void main(String[] args)
{
// array declaration
int ar[] = { 10, 50, 60, 80, 90 };
for (int element :ar)
Siddhant College Of Engineering
The Java break statement 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:
1. jump-statement;
2. break;
}
}
Continue:
The continue statement in Java is used to skip the current iteration of a loop. We can use
continue statement inside any types of loops such as for, while, and do-while loop.
Basically continue statements are used in the situations when we want to continue the loop
but do not want the remaining statement after the continue statement.
Syntax:
continue;
}
}
The break statement is used to terminate the The continue statement is used to skip the
loop immediately. current iteration of the loop.
break keyword is used to indicate break continue keyword is used to indicate continue
statements in java programming. statement in java programming.
We can use a break with the switch We can not use a continue with the switch
statement. statement.
The break statement terminates the whole The continue statement brings the next
loop early. iteration early.
It stops the execution of the loop. It does not stop the execution of the loop.
labeled loop
A label is a valid variable name that denotes the name of the loop to where the control of
execution should jump. To label a loop, place the label before the loop with a colon at the
end. Therefore, a loop with the label is called a labeled loop.
In layman terms, we can say that label is nothing but to provide a name to a loop. It is a good
habit to label a loop when using a nested loop. We can also use labels
with continue and break statements.
Siddhant College Of Engineering
Labeling a for loop is useful when we want to break or continue a specific for loop according
to requirement. If we put a break statement inside an inner for loop, the compiler will jump
out from the inner loop and continue with the outer loop again.
What if we need to jump out from the outer loop using the break statement given inside the
inner loop? The answer is, we should define the label along with the colon(:) sign before the
loop.
Syntax:
1. labelname:
2. for(initialization; condition; incr/decr)
3. {
4. //functionality of the loop
5. }
18. }
19. }
20. }
21. }
Syntax:
1. labelName:
2. while ( ... )
3. {
4. //statements to execute
5. }
Nested loop means a loop statement inside another loop statement. That is why nested
loops are also called as “loop inside loop“.
while(condition) {
while(condition) {
What is a Constructor?
A constructor in Java is similar to a method that is invoked when an object of the class is
created.
Unlike Java methods, a constructor has the same name as that of the class and does not have
any return type. For example,
class Test {
Test() {
// constructor body
classconstructor {
private String name;
// constructor
constructor() {
Siddhant College Of Engineering
System.out.println("Constructor Called:");
name = "Hello";
}
publicstaticvoidmain(String[] args) {
constructorobj = newconstructor();
System.out.println("The name is " + obj.name);
}
}
Types of Constructor
1. Parameterized Constructor
2. Default Constructor
A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructor with parameters).
classMain {
String languages;
publicstaticvoidmain(String[] args) {
publicclassMain{
int x;
publicMain(int y){
x = y;
publicstaticvoidmain(String[]args){
MainmyObj=newMain(5);
System.out.println(myObj.x);
publicclassMain{
intmodelYear;
StringmodelName;
modelYear= year;
modelName= name;
}
Siddhant College Of Engineering
publicstaticvoidmain(String[]args){
MainmyCar=newMain(1969,"Mustang");
System.out.println(myCar.modelYear+" "+myCar.modelName);
1. class Student4{
2. int id;
3. String name;
4. //creating a parameterized constructor
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. //method to display the values
10. void display(){System.out.println(id+" "+name);}
11.
12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20. }
If we do not create any constructor, the Java compiler automatically create a no-arg
constructor during the execution of the program. This constructor is called default
constructor.
Siddhant College Of Engineering
classMain {
int a;
boolean b;
publicstaticvoidmain(String[] args) {
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
publicclassMain{
publicMain(){
publicstaticvoidmain(String[]args){
MainmyObj=newMain();// Create an object of class Main (This will call the constructor)
4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){System.out.println(id+" "+name);}
8.
9. public static void main(String args[]){
10. //creating objects
11. Student3 s1=new Student3();
12. Student3 s2=new Student3();
13. //displaying values of the object
14. s1.display();
15. s2.display();
16. }
17. }
Siddhant College Of Engineering
Nesting of Methods
When a method in java calls another method in the same class, it is called Nesting of
methods.
Syntax:
class Main
{
method1(){
// statements
}
method2()
{
// statements
Enter length, breadth and height as input. After that we first call the volume method. From
volume method we call area method and from area method we call perimeter method. Hence
we get perimeter, area and volume of cuboid as output.
1. importjava.util.Scanner;
2. publicclassNesting_Methods
3. {
4. intperimeter(int l, int b)
5. {
6. intpr=12*(l + b);
7. returnpr;
8. }
9. intarea(int l, int b)
10. {
11. intpr=perimeter(l, b);
12. System.out.println("Perimeter:"+pr);
13. intar=6* l * b;
14. returnar;
15. }
16. intvolume(int l, int b, int h)
17. {
18. intar=area(l, b);
19. System.out.println("Area:"+ar);
20. intvol ;
21. vol = l * b * h;
22. return vol;
23. }
24. publicstaticvoidmain(String[]args)
25. {
26. Scanner s =newScanner(System.in);
27. System.out.print("Enter length of cuboid:");
28. int l =s.nextInt();
29. System.out.print("Enter breadth of cuboid:");
30. int b =s.nextInt();
31. System.out.print("Enter height of cuboid:");
32. int h =s.nextInt();
33. Nesting_Methodsobj=newNesting_Methods();
34. int vol =obj.volume(l, b, h);
35. System.out.println("Volume:"+vol);
36. }
37. }
Siddhant College Of Engineering
this Keyword
In Java, this keyword is used to refer to the current object inside a method or a constructor.
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Siddhant College Of Engineering
Java command-line argument is an argument i.e. passed at the time of running the Java
program. In the command line, the arguments passed from the console can be received in
the java program and they can be used as input.
The users can pass the arguments during the execution bypassing the command-line
arguments inside the main() method.
We need to pass the arguments as space-separated values. We can pass both strings and
primitive data types(int, double, float, char, etc) as command-line arguments. These
arguments convert into a string array and are provided to the main() function as a string
array argument.
Siddhant College Of Engineering
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
classMain {
publicstaticvoidmain(String[] args) {
System.out.println("Command-Line arguments are");
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
Siddhant College Of Engineering
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
Syntax:
finalize() method in Java is a method of the Object class that is used to perform cleanup
activity before destroying any object. It is called by Garbage collector before destroying the
objects from memory.
Siddhant College Of Engineering
finalize() method is called by default for every object before its deletion. This method
helps Garbage Collector to close all the resources used by the object and helps JVM in-
memory optimization.
In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces,
variables, methods, constructors, data members, and the setter methods.
classAnimal {
publicvoidmethod1() {...}
privatevoidmethod2() {...}
}
In the above example, we have declared 2 methods: method1() and method2(). Here,
class BaseClass
{
void display() //no access modifier indicates default modifier
{
System.out.println("BaseClass::Display with 'dafault' scope");
}
}
Siddhant College Of Engineering
class Main
{
public static void main(String args[])
{
//access class with default scope
BaseClassobj = new BaseClass();
classA
{
publicvoiddisplay()
{
System.out.println("SoftwareTestingHelp!!");
}
}
classMain
{
publicstaticvoidmain(String args[])
{
Aobj = newA ();
obj.display();
}
}
Siddhant College Of Engineering
class A
{
protected void display()
{
System.out.println("SoftwareTestingHelp");
}
}
class B extends A {}
class C extends B {}
class Main{
public static void main(String args[])
{
B obj = new B(); //create object of class B
obj.display(); //access class A protected method using obj
C cObj = new C(); //create object of class C
cObj.display (); //access class A protected method using cObj
}
}
Siddhant College Of Engineering
class TestClass{
//private variable and method
private int num=100;
private void printMessage(){System.out.println("Hello java");}
In Java, the Object class is considered the parent class for all the classes.
It simply means that all the classes in Java are derived/subclasses and their base class is
Object class.
All the classes directly or indirectly inherit from the Object class in Java.
Object class is present in java.lang package. Every class in Java is directly or indirectly
derived from the Object class.
The object class is the topmost class which is the base class for all the classes.
Siddhant College Of Engineering
1. toString() method
As each class is a sub-class of the Object class in Java. So the toString() method gets
inherited by the other classes from the Object class.
If we try to print the object of any class, then the JVM internally invokes
the toString() method.
2.hashCode()
A hash code is an integer value that gets generated by the hashing algorithm. Hash code is
associated with each object in Java and is a distinct value. It converts an object's internal
address to an integer through an algorithm. It is not the memory address, it is the integer
representation of the memory address.
Siddhant College Of Engineering
This method compares two objects and returns whether they are equal or not. It is used to
compare the value of the object on which the method is called and the object value which is
passed as the parameter.
4.getClass()
It is used to return the class object of this object. Also, it fetches the actual runtime class of
the object on which the method is called. This is also a native method. It can be used to get
the metadata of the this class. Metadata of a class includes the class name, fields name,
methods, constructor, etc.
5.clone()
The clone() method is used to create an exact copy of this object.
It creates a new object and copies all the data of the this object to the new object.
6.notify()
The notify() method is used to wake up only one single thread that is waiting on the object,
and that thread starts the execution.
7.notifyAll()
The notifyAll() method is used to wake up all threads that are waiting on this object. This
method gives the notification to all waiting threads of an object.
8.wait()
The wait() method tells the current thread to give up the lock and go to sleep.
9.finalize() method
This method is called just before an object is garbage collected. It is called the Garbage
Collector on an object when the garbage collector determines that there are no more
references to the object. We should override finalize() method to dispose of system
resources, perform clean-up activities and minimize memory leaks.
Siddhant College Of Engineering
Java Arrays
Normally, an array is a collection of similar type of elements which has 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.
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 every program, to use an array, we need to create it before it is used. We require two things
to create an array in Java - data type and length.
As we know, an array is a homogenous container that can only store the same type of data.
Hence, it's required to specify the data type while creating it. Moreover, we also need to put
the number of elements the array will store.
Syntax:
datatype[] arrayName = new datatype[length]; OR
datatype arrayName[] = new datatype[length];
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.
Siddhant College Of Engineering
Disadvantages
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.
An array that has only one subscript or one dimension is known as a single-dimensional
array. It is just a list of the same data type variables.
One dimensional array can be of either one row and multiple columns or multiple rows
and one column.
}
}
2. Multi-Dimensional Array
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:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
Creating a String
There are two ways to create string in Java:
String literal
String s = “GeeksforGeeks”;
Using new keyword
String s = new String (“GeeksforGeeks”);
Siddhant College Of Engineering
Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.
StringBuffer is a peer class of String that provides much of the functionality of strings.
The string represents fixed-length, immutable character sequences while StringBuffer
represents growable and writable character sequences. StringBuffer may have characters
and substrings inserted in the middle or appended to the end.
capacity() the total allocated capacity can be found by the capacity( ) method
This method returns the char value in this sequence at the specified
charAt() index.
Java Vector
Vector is like the dynamic array which can grow or shrink its size.
It is a part of Java Collection framework since Java 1.2. It is found in the java.util package
and implements the List interface,
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections
framework.
o Vector implements a dynamic array which means it can grow or shrink as required.
Like an array, it contains components that can be accessed using an integer index.
o They are very similar to ArrayList, but Vector is synchronized and has some legacy
methods that the collection framework does not contain.
o Syntax:
o public class Vector<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable
o Here, E is the type of element.
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
Siddhant College Of Engineering
The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Siddhant College Of Engineering
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer,
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing
//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}
Siddhant College Of Engineering
Java Enums
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.
According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.
Enums are used to create our own data type like classes.
The enum data type (also known as Enumerated Data Type) is used to define an enum in
Java.
Siddhant College Of Engineering
The enum can be defined within or outside the class because it is similar to a class.
Example :
class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}
Example 2:
class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
//printing all enum
for (Season s : Season.values()){
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());
}}
Siddhant College Of Engineering
The Java compiler internally adds the values() method when it creates an enum. The values()
method returns an array containing all the values of the enum.
The Java compiler internally adds the valueOf() method when it creates an enum. The
valueOf() method returns the value of given constant enum.
The Java compiler internally adds the ordinal() method when it creates an enum. The
ordinal() method returns the index of the enum value.
Java HashMap
HashMap in Java is a part of the collections framework, which is found in java.util package.
It provides the basic implementation of Map interface of Java. It stores the data in a key-
value mapping in which every key is mapped to exactly one value of any data type.
Keys should be unique as the key is used to retrieve the corresponding value from the map.
Since Java 5, it is denoted as HashMap<K,V>, where K stands for Key and V for Value.
HashMap is unsynchronised, therefore it's faster and uses less memory than HashTable.
Being unsynchronized means HashMap doesn’t guarantee any specific order of the elements.
Syntax:
Siddhant College Of Engineering
Parameters:
1. K: It is the data type of keys maintained by the map. Keys should be unique.
2. V: It is the data type of values maintained. Values need not be unique. It can be
duplicate.
Add elements
Access elements
Change elements
Remove elements
Example
import java.util.HashMap;
class Main {
// create a hashmap
Siddhant College Of Engineering
languages.put("Java", 8);
languages.put("JavaScript", 1);
languages.put("Python", 3);
Example
importjava.util.HashMap;
publicclassMain{
Siddhant College Of Engineering
publicstaticvoidmain(String[]args){
HashMap<String,String>capitalCities=newHashMap<String,String>();
capitalCities.put("England","London");
capitalCities.put("Germany","Berlin");
capitalCities.put("Norway","Oslo");
capitalCities.put("USA","Washington DC");
System.out.println(capitalCities);
Example
Create a HashMap object called people that will store String keys and Integer values:
importjava.util.HashMap;
Siddhant College Of Engineering
publicclassMain{
publicstaticvoidmain(String[]args){
people.put("John",32);
people.put("Steve",30);
people.put("Angie",33);
for(Stringi:people.keySet()){
}
Siddhant College Of Engineering
Inheritance in Java
Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.
Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template or
blueprint or prototype from which objects are created.
Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
Siddhant College Of Engineering
Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass can add its
own fields and methods in addition to the superclass fields and methods.
The extends keyword is used for inheritance in Java. Using the extends keyword indicates
you are derived from an existing class. In other words, “extends” refers to increased
functionality.
Syntax :
Example: In the below example of inheritance, class Bicycle is a base class, class
MountainBike is a derived class that extends the Bicycle class and class Test is a driver class
to run the program.
// concept of inheritance
// base class
class Bicycle {
{
Siddhant College Of Engineering
this.gear = gear;
this.speed = speed;
speed -= decrement;
speed += increment;
// derived class
int startHeight)
super(gear, speed);
seatHeight = startHeight;
seatHeight = newValue;
+ seatHeight);
// driver class
{
Siddhant College Of Engineering
System.out.println(mb.toString());
Output
No of gears are 3
speed of bicycle is 100
seat height is 25