Java Oops
Java Oops
Java Oops
Object-Oriented Programming
Object-oriented programming can be defined as a programming model which is based upon the concept of
objects. Objects contain data in the form of attributes and code in the form of methods. In object-oriented
programming, computer programs are designed using the concept of objects that interact with the real
world. Object-oriented programming languages are various but the most popular ones are class-based,
meaning that objects are instances of classes, which also determine their types.
Languages used in Object-Oriented Programming: Java, C++, C#, Python, PHP, JavaScript, Ruby,
Perl, Objective-C, Dart, Swift, Scala.
Procedural Programming vs Object-Oriented
Programming
In procedural programming, the program is divided into small parts In object-oriented programming, the program is divided into small
called functions. parts called objects.
Procedural programming follows a top-down approach. Object-oriented programming follows a bottom-up approach.
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any proper way of hiding Object-oriented programming provides data hiding so it is more
data so it is less secure. secure.
In procedural programming, there is no concept of data hiding and In object-oriented programming, the concept of data hiding and inheritance is
inheritance. used.
In procedural programming, the function is more important than the data. In object-oriented programming, data is more important than function.
Procedural programming is based on the unreal world. Object-oriented programming is based on the real world.
Procedural programming uses the concept of procedure abstraction. Object-oriented programming uses the concept of data abstraction.
Code reusability absent in procedural programming, Code reusability present in object-oriented programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
What is OOP?
A class is a template that consists of the data members or variables and functions and defines the properties and methods for a group of objects.
The compiler does not allocate memory whenever you define a class.
Example:
You can define a class called Vehicle. Its data fields can be vehicle_name, model_number, color, date_of_manufacture, etc.
An object is nothing but an instance of a class. Each object has its values for the different properties present in its class. The compiler allocates memory for each
Example:
The different objects of the class Vehicle can be Car, Bike, Bicycle, etc. Each of them will have its values for the fields like color, model_number, etc.
Abstraction
Abstraction
The literal meaning of abstraction is to remove some characteristics from something to reduce it to a smaller set. Similarly,
Object Oriented Programming abstraction exposes only the essential information of an object to the user and hides the other
details.
In real life, like when you toggle a switch, it simply turns on or off the lights. Here, we only know the functionality of the switch,
but we don’t know its internal implementation, like how it works.
How to implement abstraction?
You can implement abstraction using classes that group the data members and function together. Inside classes, you can choose
the access specifiers for its members to control how they are visible to the outside world. We can also create header files
containing the implementations of all the necessary functions. So, you can include the header file and call these functions without
getting into their implementation.
Advantages of Abstraction
The advantages of abstraction are as follows:
• It enables code reuse by avoiding code duplication.
• It enhances software security by making only necessary information available to the users and hiding the complex ones.
Inheritance
Inheritance
Inheritance is one of the most important features of object oriented programming. It allows a
class to inherit the properties and methods of another class called the parent class, the base
class, or the super-class.
The class that inherits is called the child class or sub-class.
It helps to avoid duplication of codes by allowing code reuse as you need not define the same
methods and properties present in a super-class in the sub-classes again. The sub-class can
simply inherit them.
Example:
You can have a parent class called “Shape” and other classes like
Square, Circle, Rectangle, etc. Since all these are also shapes,
they will have all the properties of a shape so that they can inherit
the class Shape
Polymorphism
Polymorphism
The word polymorphism means to have many forms. So, by using polymorphism, you can
add different meanings to a single component.
There are two types of polymorphism:
• Run-time polymorphism
• Compile-time polymorphism
Method Overloading
Methods overloading is a type of compile-time polymorphism using which you can define various functions
with the same name but different numbers of arguments. The function call is resolved at compile time, so it's a
type of compile-time polymorphism. Here resolution of the function call implies binding to the correct
function definition depending on the arguments passed in the function call.
Example:
You can create a function “add”. Now, when you pass two integers to this function, it will return their sum,
while on passing two strings, it will return their concatenation.
So, the same function acts differently depending on the input data type.
Method Overriding
Method Overriding is a type of run-time polymorphism. It allows overriding a parent class’s method by a child
class. Overriding means that a child class provides a new implementation of the same method it inherits from
the parent class.
These function calls are resolved at run-time, so it's a type of runtime polymorphism.
Example:
You can have a parent class called “Shape” with a method named “findArea” that calculates and returns the
area of the shape. Several sub-classes inherit from the “Shape,” like Square, Circle, Rectangle, etc. Each of
them will define the function “findArea” in its way, thus overriding the function.
Encapsulation
Encapsulation
Encapsulation means enclosing the data/variables and the methods for manipulating the
data into a single entity called a class. It helps to hide the internal implementation of the
functions and state of the variables, promoting abstraction.
Example:
You can have some private variables in a class that you can't access outside the class for
security reasons. Now, to read or change the value of this variable, you can define public
functions in the class which will perform the read or writes operations.
Other Oops Features:
Dynamic Binding
Dynamic binding takes place during run time based on the type of object. Since it is
delayed till the run time, it is also called late binding or runtime binding. When the
compiler cannot determine all the information required to resolve a function call during
compile time, these function calls are not bound until run time.
Message Passing
Message passing refers to the process of passing a message, or data, between different
objects or components in a program. This can be done in many ways, such as function
calls, events, or inter-process communication. The specific implementation of message
passing will depend on the program's design and the system's needs.
Advantages of Object Oriented
Programming
The advantages of object oriented programming are as follows:
• It makes troubleshooting easier and faster by making the code modular. So, you can look at
the particular class or method whenever an error occurs instead of checking the entire
code.
• It enables flexibility through polymorphism as one function or object can adapt to several
forms according to the requirement.
• It allows you to solve a problem efficiently by breaking a huge problem into smaller
manageable parts like classes and objects.
Disadvantages of Object Oriented Programming
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.
1. //Java Program to illustrate how to define a class and fields
2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
Object and Class Example: main outside the class
1. //Java Program to demonstrate having the main method in
2. //another class
3. //Creating Student class.
4. class Student{
5. int id;
6. String name;
7. }
8. //Creating another class TestStudent1 which contains the main method
9. class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
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.
1.
class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
1. We can also create multiple objects and store information in it through reference variable.
class Student{
2. int id;
3. String name;
4. }
5. class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. s1.id=101;
12. s1.name="Sonoo";
13. s2.id=102;
14. s2.name="Amit";
15. //Printing data
16. System.out.println(s1.id+" "+s1.name);
17. System.out.println(s2.id+" "+s2.name);
18. }
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.
1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19. }
According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language.
Simple
Object-Oriented: Basic concepts of OOPs are: Object, Class, Inheritance, Polymorphism, Abstraction,
Encapsulation
Portable
Platform independent: Write Once and Run Anywhere (WORA) language.
Secured: Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java
classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of
the local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
Cont…
Robust The English mining of Robust is strong. Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make Java robust.
Architecture neutral
Interpreted
High Performance
Multithreaded: A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Distributed
Dynamic: Java is a dynamic language. It supports the dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Compilation and Execution of a Java
Program
Compilation and Execution of a Java
Java, being a platform-independent programming language, doesn’t work on the one-step
Program
compilation. Instead, it involves a two-step execution, first through an OS-independent
compiler; and second, in a virtual machine (JVM) which is custom-built for every operating
system.
The two principal stages are explained below:
Principle 1: Compilation
First, the source ‘.java’ file is passed through the compiler, which then encodes the source
code into a machine-independent encoding, known as Bytecode. The content of each class
contained in the source file is stored in a separate ‘.class’ file.
Principle 2: Execution
The class files generated by the compiler are independent of the machine or the OS, which
allows them to be run on any system. To run, the main class file (the class that contains the
method main) is passed to the JVM and then goes through three main stages before the final
machine code is executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
Compilation and Execution of a Java
Program
Stage 1: Class Loader: The main class is loaded into the memory bypassing its ‘.class’ file to the
JVM, through invoking the latter. All the other classes referenced in the program are loaded through
the class loader.
Stage 2: Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode
verifier, whose job is to check that the instructions don’t perform damaging actions. The following
are some of the checks carried out:
• Variables are initialized before they are used.
• Method calls match the types of object references.
• Rules for accessing private data and methods are not violated.
• Local variable accesses fall within the runtime stack.
• The run-time stack does not overflow.
• If any of the above checks fail, the verifier doesn’t allow the class to be loaded.
Stage 3: Just-In-Time Compiler
Java Data type and Identifier
Java language has a rich implementation of data types. Data types specify size and the type of
values that can be stored in an identifier.
Java data types are classified into two categories :
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double. In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.
A primitive type can be defined as:
• They are predefined by the programming language.
• They can only store single values.
• They do not share state with other primitive values. Two variables of the reference or non-primitive type can
refer to the same object. But two primitive variables cannot affect one another.
1. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
boolean
The data type boolean is used to represent one bit of information. It can have value,
either true or false. The size of the boolean data type is machine-dependent. The boolean
data types are not typecasted into any other type implicitly or explicitly.
Declaration: boolean var;
Size: 1 bit
Range of Values: either 0 or 1
Programme:
public class BoolTest
{ public static void main(String args[])
{ boolean var = true;
if (b == true)
System.out.println("Testing Boolean Data
Type!!"); } }
// The default value of boolean data type is false
or 0
int
The int data type is a 32-bit signed two’s complement integer. Unless there is no issue with
memory, the int data type is usually chosen as the default data type for integral numbers.
Declaration: int var;
Size: 4 byte
Range of values: The range of its values is -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive).
byte
byte data type is an 8-bit signed integer. It is used in place of the int data type when we
need to save memory.
Declaration: byte var;
Size: 1 byte
Range of values: The range of its values is -128 to 127 (inclusive).
short
short data type is a 16-bit signed integer. Similar to bytes, short is also used to save
memory in large arrays.
Declaration: short var;
Size: 2 bytes
Range of values: The range of its values is -32,768 to 32,767 (inclusive).
long
When a program needs to store large integer values. Values that are out of the range of int,
then a long data type is used. The default value of long data type in Java is 0.
Declaration: long var;
Size: 8 bytes
Range of values: The range of its values is -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive).
This data type is used to store floating-point numbers associated with the single-precision
32-bit IEEE 754 values. The default value of the float data type is 0.0.
Note: IEEE 754 is IEEE Standard for Binary Floating-Point Arithmetic.
Declaration: float var;
SIze: 4 bytes
Range of Values: float variable can hold values up to 7 decimal digits.`
double
This data type is used to store floating-point numbers associated with the double-precision
64-bit IEEE 754 values. The default value of the double data type is 0.0.
Declaration: double var;
Size: 8 bytes
Range of Values: double variables can hold a value up to 16 decimal digits.
The char data type is used to store a single character, letter or ASCII value. The character
must be inside single quotes, like ‘A’ or ‘X’.
Declaration: char var;
Size: 2 bytes
Range of values: The range of its values is ‘\u0000’ (0) to ‘\uffff’ (65535).
Non-Primitive Types
• Unlike primitive data types, non-primitive data types are not predefined in the Java
language.
• These data types are used to store a group of values. Examples of non-primitive data types
are strings, objects, arrays, etc.
• When we define a variable of a non-primitive data type, it refers to a memory location
where an object is stored. That’s why non-primitive data types are also known
as Referenced Data types.
• The Java programming language provides exceptional support for character strings via the
java.lang.String class. By enclosing your character string in double quotes, a new String
object will be created automatically.
• The String class is not a primitive data type. We’ll probably think of it as such because of
the specific support it gets from the language.
Java Tokens
Tokens are the smallest units in a program that the compiler recognises. Tokens are divided
into five categories in the Java language:
• Keywords
• Identifiers
• Literals or Constants
• Operator
• Separator
• Comments
Identifiers
A class name, method name, variable name, or label is known as identifiers in Java. Identifiers are used
to identify names in programming languages.
Consider the following program:
public class Test
{
public static void main(String[] args)
{ int num = 10;
}
}
2. Identifiers should not start with digits i.e [0-9]. For example, 7num is not a valid Java identifier.
3. Identifiers in Java are case-sensitive. For example, num is not the same as Num identifier.
4. There is no hard and fast rule for the length of the identifier. But to use an identifier of the optimum length (4 – 15
letters) is considered a good practice.
5. Reserved words or Keywords can’t be used as an identifier. For example, int final = 9; is an invalid statement as final
is a reserved word. Note: There are 53 keywords in Java.
6. There should not be any space in the identifier. For example, roll no is an invalid identifier.
Keywords
Keywords are known as reserved words in programming languages. They are used to indicate
predefined terms and actions in a program. As a result, these words are not permissible to be used as
variable names or objects.
Java contains a list of keywords which includes the following:
abstract assert boolean break byte
•Some of the keywords are obsolete in Java but still come under reserved words. For example, const and goto.
•Some of the literals look like keywords in general but they are literals having a constant value. For
example: true, false and null. Note: A Literal is a constant value that can be assigned to a variable in a program.
•SQL keywords are also treated as reserved words, but they are not added to the list of keywords yet.
Difference between Keywords and
Keywords identifiers Identifiers
Keywords are predefined reserved words in Identifiers are the names used to define terms such
programming languages. as variables, integers etc.
int, char, if, while, do, class etc. are examples of num1, count2, speed_car1, etc. are examples of
Keywords identifier
Type Casting in Java
Typecasting is the process of assigning a value of one primitive data type to another type.
In Java, typecasting is of two types:
Widening Primitive Casting:
Converting lower data types into higher data types is called widening casting. No loss of information
because we are passing a smaller size type to a larger size type .
byte -> short -> char -> int -> long -> float -> double
The conversion from numeric to char or Boolean data types is not done automatically. The char and Boolean
data types are incompatible. In the program below, int is typecast into long and long into a float data type.
public class WideningCastingExample
{ public static void main(String[] args)
{
int x = 7; //Converting the integer type into long type
long y = x; //Converting the long type into float type
float z = y;
System.out.println("Before conversion, int value " + x);
System.out.println("After conversion, long value " + y);
System.out.println("After conversion, float value " +
z); } }
Output:
Before conversion, int value 7
After conversion, long value 7
Narrowing Primitive Casting:
Converting higher data types into lower data types is called narrowing
casting. Loss of information may occur. It must be done manually by
specifying the type in parentheses in front of the value.
double-> float -> long -> int -> char -> short -> byte
The constants are used in Java to make the program easy to understand and readable. Since
constant variables are cached by application and JVM, it improves the performance of an
application by making it efficient.
public class Declaration {
static final double PI = 3.14;
public static void main(String[] args) {
System.out.println("Value of PI: " + PI);
}
}
Declaring Constant as Private
class ClassA {
private static final double PI = 3.14;
}
public class ClassB {
public static void main(String[] args) {
System.out.println("Value of PI: " + ClassA.PI);
}
}
Output:
Main.java:10: error: PI has private access in Main2
System.out.println("Value of PI: " + Main2.PI);
Declaring Constant as Public
class ClassA {
public static final double PI = 3.14;
}
public class ClassB {
public static void main(String[] args) {
System.out.println("Value of PI: " + ClassA.PI);
}
}
Output: Value of PI: 3.14
Using Enumeration (Enum) as Constant
• It is the same as the final variables.
• It is a list of constants.
• Java provides the enum keyword to define the enumeration.
• It defines a class type by making enumeration in the class that may contain instance variables,
methods, and constructors.
public class EnumExample
{
//defining the enum
public enum Color {Red, Green, Blue, Purple, Black, White, Pink, Gray}
public static void main(String[] args)
{
//traversing the enum
for (Color c : Color.values())
System.out.println(c);
}
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Java Unary Operator
}
Java
Arithmetic Operators
public class MyClass {
}
The Java right shift operator >> is used to move the value of the left operand to right by
the number of bits specified by the right operand.
1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It checks
the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition
only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
Java Ternary operator is used as one line replacement for if-then-else statement and used a
lot in Java programming. It is the only conditional operator which takes three operands.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value on its r
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
Java Decision Making And Branching
“Decision making and branching” is one of the most important concepts of computer
programming. Programs should be able to make logical (true/false) decisions based on the
condition provided. So controlling the execution of statements based on certain condition
or decision is called decision making and branching.
1.If Statements
The if statement is used to test the condition. It checks boolean conditions true or false.
There are various types of if statements in Java.
• Simple if statement
• if-else statement
• if-else-if ladder
• nested if statement
i) Simple if Statement :
The Java if statement tests the condition. It executes the *if block* if the condition is
true. Where boolean_expression is a condition.
Syntax:
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}
Statement-X;
Example:
public class Branching {
Example:
public class Branching {
Example:
public class Branching{
if (num == 10) {
System.out.print("Value of num is 10");
} else if (num == 20) {
System.out.print("Value of num is 20");
} else if (num == 30) {
System.out.print("Value of num is 30");
} else {
System.out.print("This is else statement");
iv) nested if statement :
The nested if statement represents the if block within another if block. Here, the inner
if block condition executes only when the outer if block condition is
Syntax:
switch(expression) {
case value :
// Statements
break;
case value :
// Statements
break;
Example:
public class Switching {
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Good");
break;
case 'C' :
System.out.println("Well done");
break;
default :
System.out.println("Invalid grade");
}
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.
The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte,
Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.
Points to Remember
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must be literal or constant. It doesn't
allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
• 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.
• The case value can have a default label which is optional.
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
Flowchart of Switch Statement
1. public class SwitchExample {
2. public static void main(String[] args) {
3. //Declaring a variable for switch expression
4. int number=20;
5. //Switch expression
6. switch(number){
7. //Case statements
8. case 10: System.out.println("10");
9. break;
10. case 20: System.out.println("20");
11. break;
12. case 30: System.out.println("30");
13. break;
14. //Default case statement
15. default:System.out.println("Not in 10, 20 or 30");
16. }
17. }
18. }
1. //Java Program to demonstrate the example of Switch statement
2. //where we are printing month name for the given number
3. public class SwitchMonthExample {
4. public static void main(String[] args) {
5. //Specifying month number
6. int month=7;
7. String monthString="";
8. //Switch statement
9. switch(month){
10. //case statements within the switch block
11. case 1: monthString="1 - January";
12. break;
13. case 2: monthString="2 - February";
14. break;
15. case 3: monthString="3 - March";
16. break;
17. case 4: monthString="4 - April";
18. break;
19. case 5: monthString="5 - May";
20. break;
21. case 6: monthString="6 - June";
22. break;
23. case 7: monthString="7 - July";
24. break;
25. case 8: monthString="8 - August";
26. break;
27. case 9: monthString="9 - September";
28. break;
29. case 10: monthString="10 - October";
30. break;
31. case 11: monthString="11 - November";
32. break;
33. case 12: monthString="12 - December";
34. break;
35. default:System.out.println("Invalid Month!");
36. }
Java Switch Statement is fall-through
The Java switch statement is fall-through. It means it executes all statements after the first match if a
1. //Java Switch Example where we are omitting the
2. //break statement
3. public class SwitchExample2 {
4. public static void main(String[] args) {
5. int number=20;
6. //switch expression with int value
7. switch(number){
8. //switch cases without break statements
9. case 10: System.out.println("10");
10. case 20: System.out.println("20");
11. case 30: System.out.println("30");
12. default:System.out.println("Not in 10, 20 or 30");
13. }
14. }
Loops in Java
for loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use
for loop.
There are three types of for loops in Java.
• Simple for Loop
• For-each or Enhanced for Loop
• Labeled for Loop
Java Simple for Loop
A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists
of four parts:
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.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
1. for(initialization; condition; increment/decrement){
2. //statement or code to be executed
1. //Java Program to demonstrate the example of for loop
2. //which prints table of 1
3. public class ForExample {
4. public static void main(String[] args) {
5. //Code of Java for loop
6. for(int i=1;i<=10;i++){
7. System.out.println(i);
8. }
9. }
10. }
Java 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:
NestedForExample.java
1. public class NestedForExample {
2. public static void main(String[] args) {
3. //loop of i
4. for(int i=1;i<=3;i++){
5. //loop of j
6. for(int j=1;j<=3;j++){
7. System.out.println(i+" "+j);
8. }//end of i
9. }//end of j
10. }
11. }
1. public class PyramidExample {
2. public static void main(String[] args) {
3. for(int i=1;i<=5;i++){
4. for(int j=1;j<=i;j++){
5. System.out.print("* ");
6. }
7. System.out.println();//new line
8. }
9. }
10. }
Java for-each Loop
The for-each loop is used to traverse array or collection in Java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one by one in the
defined variable.
Syntax:
1. for(data_type variable : array_name){
2. //code to be executed
3. }
1. //Java For-each loop example which prints the
2. //elements of the array
3. public class ForEachExample {
4. public static void main(String[] args) {
5. //Declaring an array
6. int arr[]={12,23,44,56,78};
7. //Printing array using for-each loop
8. for(int i:arr){
9. System.out.println(i);
10. }
11. }
12. }
Java Labeled For Loop
1. //A Java program to demonstrate the use of labeled for loop
2. public class LabeledForExample {
3. public static void main(String[] args) {
4. //Using Label for outer and for loop
5. aa:
6. for(int i=1;i<=3;i++){
7. bb:
8. for(int j=1;j<=3;j++){
9. if(i==2&&j==2){
10. break aa;
11. }
12. System.out.println(i+" "+j);
13. }
14. }
15. }
16. }
1. public class LabeledForExample2 {
2. public static void main(String[] args) {
3. aa:
4. for(int i=1;i<=3;i++){
5. bb:
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. break bb;
9. }
10. System.out.println(i+" "+j);
11. }
12. }
13. }
14. }
Java Infinitive for Loop
1. for(;;){
2. //code to be executed
3. }
Syntax:
1. do{
2. //code to be executed
3. }while(true);
Break Statement is a loop control statement that is used to terminate the loop. As soon as
the break statement is encountered from within a loop, the loop iterations stop there, and
control returns from the loop immediately to the first statement after the loop.
class BreakLoopDemo {
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++) {
// terminate loop when i is 5.
if (i == 5)
break;
3. // for loop
4. for (int i = 1; i <= 10; ++i) {
1. import java.util.Scanner;
2. class Main {
3. public static void main(String[] args) {
4. Double number, sum = 0.0;
5. // create an object of Scanner
6. Scanner input = new Scanner(System.in);
7. for (int i = 1; i < 6; ++i) {
8. System.out.print("Enter number " + i + " : ");
9. // takes input from the user
10. number = input.nextDouble();
11. // if number is negative
12. // continue statement is executed
13. if (number <= 0.0) {
14. continue;
15. }
16. sum += number;
17. }
18. System.out.println("Sum = " + sum);
19. input.close();
20. }
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. 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.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use
the sizeof operator.
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. Like C/C++, we can also create single dimentional or multidimentional arrays in
Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at an index position.
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.
Types of Array in java
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an
array.
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
1. //Java Program to illustrate the use of declaration, instantiation
2. //and initialization of Java array in a single line
3. class Testarray1{
4. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9. }}
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}
Example of Multidimensional Java Array
1. //Java Program to illustrate the use of multidimensional array
2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Addition of 2 Matrices in Java
In general, 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. In this section, we will learn what is a method in Java, types of methods,
method declaration, and how to call a method in Java.
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:
• Public: The method is accessible by all classes when we use public specifier
in our application.
• Private: When we use a private access specifier, the method is accessible only
in the classes in which it is defined.
• Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
• 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
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.
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.
Naming a Method
While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first name
must be a verb followed by adjective or noun. In the multi-word method name, the first
letter of each word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the
Types of Method
There are two types of methods in Java:
• Predefined Method
• User-defined Method
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. When
we call any of the predefined methods in our program, a series of codes related to the corresponding method runs in the
background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For example, print("Java"), it prints
Java on the console.
Let's see an example of the predefined method.
1. public class Demo
2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
In the above example, we have used three predefined methods main(), print(), and max(). We have used
these methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class
that returns the greater of two numbers.
In the above method signature, we see that the method signature has access specifier public, non-access
modifier static, return type int, method name max(), parameter list (int a, int b). In the above example,
instead of defining the method, we have just invoked the method. This is the advantage of a predefined
method. It makes programming less complicated.
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.
How to Create a User-defined Method
Let's create a user defined method that checks the number is even or odd. First, we will define the method.
1. //user defined method
2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }
How to Call or Invoke a User-defined Method
A method that has static keyword is known as static method. In other words, a method that belongs to a class rather than an
instance of a class is known as a static method. We can also create a static method by using the keyword static before the method
name.
The main advantage of a static method is that we can call it without creating an object. It can access static data members and also
change the value of it. It is used to create an instance method. It is invoked by using the class name. The best example of a static
method is the main() method.
Example of static method
Display.java
1. public class Display
2. {
3. public static void main(String[] args)
4. {
5. show();
6. }
7. static void show()
8. {
9. System.out.println("It is an example of static method.");
10. }
Instance Method
The method of the class is known as an instance method. It is a non-static method
defined in the class. Before calling or invoking the instance method, it is necessary to
create an object of its class. Let's see an example of an instance method.
1.public class InstanceMethodExample
2.{
3.public static void main(String [] args)
4.{
5.//Creating an object of the class
6.InstanceMethodExample obj = new InstanceMethodExample();
7.//invoking instance method
8.System.out.println("The sum is: "+obj.add(12, 13));
9.}
10.int s;
11.//user-defined method because we have not used static keyword
12.public int add(int a, int b)
13.{
14.s = a+b;
15.//returning the sum
16.return s;
17.}
18.}
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value.
The changes being done in the called method, is not affected in the calling method.
Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
Another Example of call by value in java
In case of call by reference original value is changed if we made changes in the called method. If we pass
object in place of any primitive value, original value will be changed. In this example we are passing object as
a value. Let's take a simple example:
1. class Operation2{
2. int data=50;
3. void change(Operation2 op){
4. op.data=op.data+100;//changes will be in the instance variable
5. }
6. public static void main(String args[]){
7. Operation2 op=new Operation2();
8. System.out.println("before change "+op.data);
9. op.change(op);//passing object
10. System.out.println("after change "+op.data);
11. }
12. }
Passing and Returning Objects in Java
O/P:
ob.a=5
// Java Program to Demonstrate Objects Passing to Methods.
// Class public class GFG {
// Helper class
public static void main(String args[])
class ObjectPassDemo { {
int a, b;
ObjectPassDemo ob1 = new
ObjectPassDemo(100, 22);
ObjectPassDemo(int i, int j) ObjectPassDemo ob2 = new
{ ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1,
a = i; -1);
b = j;
System.out.println("ob1 ==
}
ob2: "
boolean equalTo(ObjectPassDemo o) +
{ ob1.equalTo(ob2));
System.out.println("ob1 == ob3: "
return (o.a == a && o.b == b); +
} ob1.equalTo(ob3));
}
}
}
Defining a constructor that takes an object of its class as a parameter
* depth; }
}
Returning Objects
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
the current object.
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.
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.
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();
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
1.class Student{
2.int rollno;
3.String name;
4.float fee;
5.Student(int r,String n,float f){
6.rollno=r;
7.name=n;
8.fee=f;
9.}
10.void display()
{System.out.println(rollno+" "+name+" "+fee);}
11.}
12.
13.class TestThis3{
14.public static void main(String args[]){
15.Student s1=new Student(111,"ankit",5000f);
16.Student s2=new Student(112,"sumit",6000f);
17.s1.display();
18.s2.display();
19.}}
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
1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
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:
1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
Calling parameterized constructor from
default constructor:
1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
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.
1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. this.fee=fee;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis7{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this.fee=fee;
12. this(rollno,name,course);//C.T.Error
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis8{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
4) this: to pass as an argument in the method
1. 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{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
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:
1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
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:
1. return_type method_name(){
2. return this;
3. }
Example of this keyword that you return as a statement from the method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }