0% found this document useful (0 votes)
33 views

CSC ASSIGNMENT on Object Oriented Programming

assigment

Uploaded by

Zack Yusuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

CSC ASSIGNMENT on Object Oriented Programming

assigment

Uploaded by

Zack Yusuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

What is Object Oriented Programming (OOP)?

Object Oriented Programming (OOP) is a programming paradigm that focuses on the use of
objects to represent and manipulate data. In OOP, data is encapsulated within objects, and
objects are defined by their properties (attributes) and behaviors (methods). OOP provides
several key concepts that enable developers to write modular, reusable, and maintainable
code.

Definition of OOP Concepts in Java

The main ideas behind Java’s Object-Oriented Programming, OOP concepts include
abstraction, encapsulation, inheritance and polymorphism. Basically, Java OOP concepts
let us create working methods and variables, then re-use all or part of them without
compromising security. Grasping OOP concepts is key to understanding how Java works.

Java defines OOP concepts as follows:

 Abstraction. Using simple things to represent complexity. We all know how to turn
the TV on, but we don’t need to know how it works in order to enjoy it. In Java,
abstraction means simple things like objects, classes and variables represent more
complex underlying code and data. This is important because it lets you avoid
repeating the same work multiple times.
 Encapsulation. The practice of keeping fields within a class private, then providing
access to those fields via public methods. Encapsulation is a protective barrier that
keeps the data and code safe within the class itself. We can then reuse objects like
code components or variables without allowing open access to the data system-wide.
 Inheritance. A special feature of Object-Oriented Programming in Java, Inheritance
lets programmers create new classes that share some of the attributes of existing
classes. Using Inheritance lets us build on previous work without reinventing the
wheel.
 Polymorphism. Allows programmers to use the same word in Java to mean different
things in different contexts. One form of polymorphism is method overloading.
That’s when the code itself implies different meanings. The other form is method
overriding. That’s when the values of the supplied variables imply different
meanings. Let’s delve a little further.

How OOP Concepts in Java Work

OOP concepts in Java work by letting programmers create components that are reusable in
different ways while maintaining security.

How Abstraction Works

Abstraction lets programmers create useful and reusable tools. It enables programmers to
create complex systems by breaking them down into smaller, more manageable components.
For example, a programmer can create several different types of objects, which can be
variables, functions or data structures. Programmers can also create different classes of
objects as ways to define the objects.
For instance, a class of variable might be an address. The class might specify that each
address object shall have a name, street, city and zip code. The objects, in this case, might be
employee addresses, customer addresses or supplier addresses. In addition, abstraction
provides a mechanism for hiding the implementation details of a class or method from the
outside world and providing a simplified interface for clients to interact with. In Java, you
can achieve abstraction through two main mechanisms: abstract classes and interfaces.

1. Abstract Classes: An abstract class is a class that you can’t instantiate and can only
extend by subclasses. Abstract classes can have both abstract and non-abstract
methods. Abstract methods do not have a body and you must implement them by any
subclass that extends the abstract class. Non-abstract methods have a body and you
can directly call them by the subclass.
2. Interfaces: An interface is a collection of methods. You can use it to define a set of
behaviors that a class should implement. A class can implement multiple interfaces,
and all the methods defined in an interface must be implemented by any class that
implements it.

How Encapsulation Works

Encapsulation lets us reuse functionality without jeopardizing security. It’s a powerful, time-
saving OOP concept in Java. For example, we may create a piece of code that calls specific
data from a database. It may be useful to reuse that code with other databases or processes.
Encapsulation lets us do that while keeping our original data private. It also lets us alter our
original code without breaking it for others who have adopted it in the meantime.

Encapsulation provides several benefits, including:

1. Data hiding: By hiding the implementation details of a class, encapsulation protects


the data from unauthorized access and manipulation.
2. Modularity: Encapsulation helps to break down complex systems into smaller, more
manageable components, making the codebase more modular and easier to maintain.
3. Flexibility: By providing a controlled interface for interacting with a class,
encapsulation allows for changes to the internal implementation without affecting the
external interface.

Access Modifiers

In Java, encapsulation is implemented using access modifiers, which control the visibility of
variables and methods within a class.

The three access modifiers in Java are:


1. Public: Public variables and methods can be accessed from anywhere, including
outside the class.
2. Private: Private variables and methods can only be accessed within the class they are
defined in.
3. Protected: Protected variables and methods can be accessed within the same class
and its subclasses.

Encapsulation enables developers to write cleaner, more organized, and more secure code. By
controlling access to variables and methods, encapsulation promotes good software design
practices and helps to manage the complexity of large-scale projects.

How Inheritance Works

Inheritance is another labor-saving Java OOP concept that works by letting a new class adopt
the properties of another. We call the inheriting class a subclass or a child class. The original
class is often called the parent or the superclass. We use the keyword extends to define a
new class that inherits properties from an old class.

The subclass inherits all the public and protected variables and methods of the superclass, and
it can also define its own variables and methods. This makes it possible to create a hierarchy
of classes, where each subclass inherits from its superclass and adds its own unique features.

Benefits of Inheritance

Inheritance provides several benefits, including:

1. Reusability: By inheriting from a superclass, a subclass can reuse the code and
functionality already defined in the superclass, making it easier to write and maintain
code.
2. Polymorphism: Inheritance allows for polymorphism, where objects of different
subclasses can be treated as objects of the same superclass, making it easier to write
generic code.
3. Flexibility: Inheritance provides a way to add new features to an existing class
hierarchy without modifying the existing code.

Inheritance allows developers to create complex class hierarchies with shared functionality
and unique features. By promoting code reuse, polymorphism, and flexibility, inheritance
enables developers to write more efficient and maintainable code.

How Polymorphism Works

Polymorphism in Java works by using a reference to a parent class to affect an object in the
child class. We might create a class called “horse” by extending the “animal” class. That
class might also implement the “professional racing” class. The “horse” class is
“polymorphic,” since it inherits attributes of both the “animal” and “professional racing”
class.

Two more examples of polymorphism in Java are method overriding and method
overloading.
In method overriding, the child class can use the OOP polymorphism concept to override a
method of its parent class. That allows a programmer to use one method in different ways
depending on whether it’s invoked by an object of the parent class or an object of the child
class.

In method overloading, a single method may perform different functions depending on the
context in which it’s called. This means a single method name might work in different ways
depending on what arguments are passed to it.

Benefits of Polymorphism

Polymorphism provides several benefits, including:

1. Flexibility: Polymorphism allows for more flexible and adaptable code by enabling
objects of different classes to be treated as if they are of the same class.
2. Code reuse: Polymorphism promotes code reuse by allowing classes to inherit
functionality from other classes and to share common methods and properties.
3. Simplification: Polymorphism simplifies code by enabling the use of generic code
that can handle different types of objects.

Polymorphism allows for more flexible and adaptable code. By enabling objects of different
classes to be treated as if they are of the same class, polymorphism promotes code reuse,
simplification, and flexibility, making it an essential component of Object-Oriented
Programming.

Examples of OOP Concepts in Java

Now that we explained the foundational OOP concepts in Java, let’s look at a few common
examples.

Short Encapsulation Example in Java

In the example below, encapsulation is demonstrated as an OOP concept in Java. Here, the
variable “name” is kept private or “encapsulated.”

//save as Student.java
package com.javatpoint;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name
}
}
//save as Test.java
package com.javatpoint;
class Test {
public static void main(String[] args) {
Student s = new Student();
s.setName(“vijay”);
System.out.println(s.getName());
}
}
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test

Output: vijay

Example of Inheritance in Java

It’s quite simple to achieve inheritance as an OOP concept in Java. Inheritance can be as easy
as using the extends keyword:

class Mammal {

}
class Aardvark extends Mammal {

For a full tutorial on the different ways to use inheritance in java, see this blog post.

Short Example of Polymorphism in Java

In the example below of polymorphism as an OOP concept in Java, we have two classes:
Person and Employee. The Employee class inherits from the Person class by using the
keyword extends. Here, the child class overrides the parent class. For the full example, see
this blog post.

class Person {
void walk() {
System.out.println(“Can Run….”);
}
}
class Employee extends Person {
void walk() {
System.out.println(“Running Fast…”);
}
public static void main(String arg[]) {
Person p = new Employee(); //upcasting
p.walk();
}
}

Differences between OOP and other programming styles


Object-Oriented Programming (OOP) has become widely popular due to its many advantages
over other programming styles such as Procedural Programming and Functional
Programming.

Procedural Programming

Procedural Programming is a programming style that is based on a set of procedures or


functions, where each function is a sequence of instructions that performs a specific task. It
focuses on the sequence of must-follow steps that to accomplish a specific task. In contrast,
OOP focuses on the objects and their interactions to solve problems.

Functional Programming

Functional Programming is a programming style that focuses on the use of functions that
produce output based on their input, without modifying any external state. It is based on
mathematical functions and is characterized by immutability and statelessness. In contrast,
OOP is based on objects and their states, and it is designed to manage complex, stateful
systems.

Benefits of OOP over other programming

Here are some key differences between OOP and other programming styles:

1. Data and behavior: OOP is based on the idea of encapsulating data and behavior
within objects, whereas procedural programming separates data and behavior into
different functions or procedures. Functional programming, on the other hand, treats
data and behavior as separate entities altogether.
2. Inheritance and code reuse: OOP uses inheritance to reuse code and build complex
systems. Procedural programming and functional programming do not have
inheritance concepts built into them.
3. Flexibility: OOP is more flexible than procedural programming because it allows for
changes to be made to the underlying data structures and objects without changing the
entire system. In contrast, procedural programming requires a complete restructuring
of the program if any changes are made.

OOP enables encapsulation, inheritance, code reusability, and flexibility, making it a


powerful tool for building complex, stateful systems.

Best Practices for OOP Concepts in Java

The goal of OOP concepts in Java is to save time without sacrificing security and ease of use.
The following best practices are all oriented toward advancing that main goal.

 DRY (Don’t Repeat Yourself). A core concept in Java, DRY simply means you
should never have two blocks of identical code in two different places. Instead, have
one method you use for different applications.
 If you expect your Java code to change in the future, encapsulate it by making all
variables and methods private at the outset. As the code changes, increase access to
“protected” as needed, but not too public.
 Single Responsibility. This best practice principle for OOP concepts in Java states
that a class should always have only one functionality. That way, the class can be
called and/or extended on its own when new uses arise for it, without causing
coupling between different functionalities.
 Open Closed Design. Make all methods and classes Closed for modification but
Open for an extension. That way, tried and tested code can remain static but can be
modified to perform new tasks as needed.

Building Block of Object-oriented Programming

Two basic building blocks of object-oriented programming are classes and objects.

Classes

A class is a template for creating objects. It defines the data and behavior that all objects of
that type will share. In object-oriented programming, you create classes by defining a set of
properties and methods. Properties are like instance variables, except all objects of a class
share them. Methods are like functions, except objects can invoke them.

Classes can be used to model the real world. For example, you could create a class named
Car that defines the properties and methods for all cars. This class includes properties such as
make, model, and year and other methods such as start, stop and accelerate.

Classes can also be used to model abstract concepts. For example, you could create a class
named Shape that defines the properties and methods for all shapes. This class could include
properties such as width, height, and color and other methods such as rotate and translate.

Objects

In object-oriented programming, you instantiate a class by creating an object. An object can


be thought of as a particular instance of a class. It contains its own copy of each property
defined in the class, and each method is executed independently on that object.
Individual objects have their own unique identity that distinguishes them from all other
objects. In other words, no two objects are the same.

software-development-services

Principles of Object-oriented Programming

Four principles of OOP that you should know before learning any object-oriented
programming language include:

Abstraction

It is a set of rules and definitions that allows one to understand a topic or issue without
actually knowing about it in person or how it was developed.

Encapsulation

The process of combining data and behavior together into a single unit is called an object.
The data and behavior should be made hidden from the other objects and the developer. The
object can then be assigned to a variable that can be passed around as if it is an element of
code. Encapsulation allows the definition and implementation of interfaces between different
objects.

Inheritance

Allows one class, called the base or superclass, to be inherited by another class, called the
derived or child class. The child class then gains all the members of the superclass, including
data and behavior, unless they are overridden in the class. This allows for code reuse and a
more concise way of developing software.

Polymorphism

It is the ability of an object to take on different forms or be polymorphic. This is usually


achieved through inheritance, where the child class can redefine the behavior of the members
inherited from the superclass. Polymorphism allows for more flexible code and a greater
degree of abstraction.

Top List of Object-oriented Programming Languages


Our blog will go through the six object-oriented programming languages commonly used
today, including Java, C#, Ruby, Python, TypeScript, and PHP. Each of these languages has
different strengths and weaknesses, but they’re all object-oriented.

Before we go over the six OOP languages, let’s take a look at what an object-oriented
programming language is.

An object-oriented programming language is a programming language that represents the


elements of a problem as objects, which contain data and behavior. Real-world objects are
used to model the state and behavior of real-world entities in your application. Object-
oriented languages can be subdivided into categories depending on their particular type of
system, also referred to as static or dynamic typing.

ATTRIBUTE OF JAVA PROGRAMMING LANGUAGE TO OTHER HIGH LEVEL


LANGUAGE

Top 8 Java Features You Must Know

 Simple. Java is a simple programming language and easy to understand because it


does not contain complexities that exist in prior programming languages. ...
 Object-Oriented. ...
 Platform Independent. ...
 Portable. ...
 Robust. ...
 Secure. ...
 Interpreted. ...
 Multi-Threaded.

DEFINITION OF TERMS

1. Simple

Java is a simple programming language and easy to understand because it does not contain
complexities that exist in prior programming languages. In fact, simplicity was the design
aim of Javasoft people, because it has to work on electronic devices where less
memory/resources are available. Java contains the same syntax as C, and C++, so the
programmers who are switching to Java will not face any problems in terms of syntax.
Secondly, the concept of pointers has been completely removed from Java which leads to
confusion for a programmer and pointers are also vulnerable to security.

2. Object-Oriented
Java is an Object Oriented Programming Language, which means in Java everything is
written in terms of classes and objects. Now, what is an Object? The object is nothing but a
real-world entity that can represent any person, place, or thing and can be distinguished from
others. Every object near us has some state and behaviour associated with it.

For example, my mobile phone is a real-world entity and has states like colour, model, brand,
camera quality, etc, and these properties are represented by variables. Also mobile is
associated with actions like, calling, messaging, photography, etc and these actions are
represented by methods in Java.

Now, we saw what an object is and also learned about the state and behaviour associated with
the object.

What is Class? A collection of objects that exhibits the same state and behavior will come
under the same group called class. For example, Samsung, Apple, Vivo, Oppo, Xiaomi, etc
are different brands making various models of smartphones, but they all come under the same
group known as Mobile Phones.

The main concepts of any Object Oriented Programming language are given below:

1. Class and Object


2. Encapsulation
3. Abstraction
4. Inheritance
5. Polymorphism

3. Platform Independent

The design objective of javasoft people is to develop a language that must work on any
platform. Here platform means a type of operating system and hardware technology. Java
allows programmers to write their program on any machine with any configuration and to
execute it on any other machine having different configurations.

In Java, Java source code is compiled to bytecode and this bytecode is not bound to any
platform. In fact, this bytecode is only understandable by the Java Virtual Machine which is
installed in our system. What I meant to say is that every operating system has its own
version of JVM, which is capable of reading and converting bytecode to an equivalent
machine’s native language. This reduces the overhead of programmers writing system-
specific code. Now programmers write programs only once, compile them, generate the
bytecode and then export it anywhere.

4. Portable

The WORA (Write Once Run Anywhere) concept and platform-independent feature make
Java portable. Now using the Java programming language, developers can yield the same
result on any machine, by writing code only once. The reason behind this is JVM and
bytecode. Suppose you wrote any code in Java, then that code is first converted to equivalent
bytecode which is only readable by JVM. We have different versions of JVM for different
platforms. Windows machines have their own version of JVM, Linux has its own and macOS
has its own version of JVM. So if you distribute your bytecode to any machine, the JVM of
that machine would translate the bytecode into the respective machine code. In this way
portability lets the programmers focus on development and productivity rather than writing
different code for different platforms.

5. Robust

The Java Programming language is robust, which means it is capable of handling unexpected
termination of a program. There are 2 reasons behind this, first, it has a most important and
helpful feature called Exception Handling. If an exception occurs in java code then no harm
will happen whereas, in other low-level languages, the program will crash.

Another reason why Java is strong lies in its memory management features. Unlike other
low-level languages, Java provides a runtime Garbage collector offered by JVM, which
collects all the unused variables. The garbage collector is a special program under JVM that
runs from time to time and detects any unused variables and objects and removes them from
the memory to free up space. But in the case of other prior languages, there is no such
program to handle memory management, programmers are solely responsible for allocating
and deallocating memory spaces, otherwise, the program may crash due to insufficient
memory

6. Secure

In today’s era, security is a major concern of every application. As of now, every device is
connected to each other using the internet and this opens up the possibility of hacking. And
our application built using java also needs some sort of security. So Java also provides
security features to the programmers. Security problems like virus threats, tampering,
eavesdropping, and impersonation can be handled or minimized using Java. Encryption and
Decryption feature to secure your data from eavesdropping and tampering over the internet.
An Impersonation is an act of pretending to be another person on the internet. The solution to

The impersonation problem is a digital signature, a file that contains personal identification
information in an unreadable format. Digital Signature can be generated using Java. Virus is a
program that is capable of harming our system and this is generally spread with .exe files,
image files, and video files but cannot be spread using a text file the good thing is java
bytecode is also a text file (yes .class file also a text file with non-human-readable format).
Even if somebody tries to add virus code in a bytecode file, then also we are safe, because our
JVM is smart enough to distinguish viruses from normal programs. If a virus is found in a
bytecode file, JVM will throw an exception and abort execution.

7. Interpreted

In programming languages, you have learned that they use either the compiler or an
interpreter, but Java programming language uses both a compiler and an interpreter. Java
programs are compiled to generate bytecode files then JVM interprets the bytecode file
during execution. Along with this JVM also uses a JIT compiler (it increases the speed of
execution).

8. Multi-Threaded
Thread is a lightweight and independent subprocess of a running program (i.e, process) that
shares resources. And when multiple threads run simultaneously is called multithreading. In
many applications, you have seen multiple tasks running simultaneously, for example,
Google Docs where while typing text, the spell check and autocorrect tasks are running.

The server also uses multithreading to provide its services to multiple client requests. In Java,
you can create threads in two ways, either by implementing the Runnable interface or by
extending the Thread class.

Conclusion
In this article, we have discussed the design aim of Java i.e, James Gosling wants to develop
Java as a system-independent language that must work on the WORA (Write Once Run
Anywhere) principle. We also have learned the top features of Java, which makes java the
most popular among other programming languages. By now, you must have got a glimpse of
Java. Along with all this, we also discussed problems in C++, which have been resolved in
Java.

DEFINITION OF JAVA KEYWORDS


Keywords are predefined, reserved words used in Java programming that have special meanings to
the compiler. For example: int score; Here, int is a keyword.

EXAMPLES OF KEYWORDS IN JAVA

Java Reserved Keywords


Java has a set of keywords that are reserved words that cannot be used as variables, methods,
classes, or any other identifiers:

Keyword Description

A non-access modifier. Used for classes and methods: An abstract class cannot
be used to create objects (to access it, it must be inherited from another class).
abstract
An abstract method can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from)

assert For debugging

boolean A data type that can only store true and false values

break Breaks out of a loop or a switch block

byte A data type that can store whole numbers from -128 and 127

case Marks a block of code in switch statements

catch Catches exceptions generated by try statements

char A data type that is used to store a single character


class Defines a class

continue Continues to the next iteration of a loop

const Defines a constant. Not in use - use final instead

default Specifies the default block of code in a switch statement

do Used together with while to create a do-while loop

double A data type that can store whole numbers from 1.7e−308 to 1.7e+308

else Used in conditional statements

enum Declares an enumerated (unchangeable) type

exports Exports a package with a module. New in Java 9

extends Extends a class (indicates that a class is inherited from another class)

A non-access modifier used for classes, attributes and methods, which makes
final
them non-changeable (impossible to inherit or override)

Used with exceptions, a block of code that will be executed no matter if there is
finally
an exception or not

float A data type that can store whole numbers from 3.4e−038 to 3.4e+038

for Create a for loop

goto Not in use, and has no function

if Makes a conditional statement

implements Implements an interface

import Used to import a package, class or interface

instanceof Checks whether an object is an instance of a specific class or an interface

int A data type that can store whole numbers from -2147483648 to 2147483647

interface Used to declare a special type of class that only contains abstract methods

A data type that can store whole numbers from -9223372036854775808 to


long
9223372036854775808

module Declares a module. New in Java 9

Specifies that a method is not implemented in the same Java source file (but in
native
another language)

new Creates new objects

package Declares a package

private An access modifier used for attributes, methods and constructors, making them
only accessible within the declared class

An access modifier used for attributes, methods and constructors, making them
protected
accessible in the same package and subclasses

An access modifier used for classes, attributes, methods and constructors,


public
making them accessible by any other class

requires Specifies required libraries inside a module. New in Java 9

Finished the execution of a method, and can be used to return a value from a
return
method

short A data type that can store whole numbers from -32768 to 32767

A non-access modifier used for methods and attributes. Static


static
methods/attributes can be accessed without creating an object of a class

strictfp Restrict the precision and rounding of floating point calculations

super Refers to superclass (parent) objects

switch Selects one of many code blocks to be executed

A non-access modifier, which specifies that methods can only be accessed by


synchronized
one thread at a time

this Refers to the current object in a method or constructor

throw Creates a custom error

throws Indicates what exceptions may be thrown by a method

A non-accesss modifier, which specifies that an attribute is not part of an


transient
object's persistent state

try Creates a try...catch statement

var Declares a variable. New in Java 10

void Specifies that a method should not have a return value

Indicates that an attribute is not cached thread-locally, and is always read from
volatile
the "main memory"

while Creates a while loop

ANOTHER JAVA KEYWORD


#1 Data Type Keywords

Java Keywords which are used to declare variables of different data types.
1. byte : byte is a keyword used to store numbers ranging from -128 to 127.

byte num=13;

2. short : short keyword is used to store numbers ranging from -32768 to 32767.

short num= -3245;

3. int : int keyword is used to store numbers ranging from -2147483648 to 2147483647.

int num= 65783920;

4. long : long keyword is used to store numbrs ranging from -9223372036854775808L to


9223372036854775807L. A letter ‘l’ or ‘L’ should be added to tell the compiler that the
numbers is a long and not an int.

long num= 6578392546544642L;

5. char : char keyword is used to store single character/letters or ASCII values. Its value
range is from ‘\u0000’ to ‘\uffff’ or 0 to 65535. All the characters must be enclosed within
single quotes.

char var='A';

char name='\u0041';

6. boolean : boolean keyword is used to store values true or false.

boolean var=true;

7. float : float keyword is used to store fractional values ranging from -3.4028235E38F to
3.4028235E38F. A letter ‘f’ or ‘F’ should be added to tell the compiler that the fraction is a
float and not a double.
float var=-3.40282E38F;

8. double : double keyword is used to store fractional values ranging from -


1.7976931348623157 x 10308 to 1.7976931348623157 x 10308 .

double var = -1.234567543;

#2 Looping or Iterative statement Keywords

Java Keywords which are used for loops and Iterative statements.

9. for : for keyword is used to start the for loop. It is an entry-controlled loop in which the
condition is checked first, and then the loop body gets executed only if the condition is
satisfied. If the number of iterations is known already, then it is recommended to use for loop.

for(int i=0;i<=5;i++){

System.out.println(i);

10. while : while keyword is used to start the while loop. It is also an entry-controlled loop.
If the number of iterations is not known already, then it is recommended to use while loop.

int i=0;

while(i<=5){

System.out.println(i);

i++;

11. do : do keyword is used to start a do-while loop. It is used along with the while to create
a do-while loop. do-while loop is an exit-controlled loop in which, first of all the loop body
gets executed and then the condition is checked while exiting from the loop body.

int i=0;

do{
System.out.println(i);

i++;

}while(i<=5);

#3 Conditional statement Keywords

Java Keywords which are used for Conditional statements.

12. if : if keyword is used to create the if conditional statement. if the condition is true, then the if
block gets executed.

int i=0;

if(i==0){

System.out.println("Correct");

13. else : else keyword is used when the if condition becomes false, and then the else block
gets executed. It indicated the alternative branches in an if statement.

int i=1;

if(i==0){

System.out.println("Correct");

else{

System.out.println("Wrong");

14. switch : switch keyword is used to create the switch statement, which is used to execute
different cases based on test value.

switch (number){

case 1:

System.out.println("inside case 1");


break;

default:

System.out.println("inside default case");

15. case : case keyword is used inside the switch-case block to create each case.

switch (number){

case 1:

System.out.println("inside case 1");

break;

case 2:

System.out.println("inside case 2");

break;

16. default : default keyword is used inside the switch-case block. If non of the cases
matches, then the default block gets executed.

switch (number){

case 1:

System.out.println("inside case 1");

break;

default:

System.out.println("inside the default block");

17. continue : continue keyword is used to skip the statement following it inside the loop
body and moves the control to the end of the loop body, and the control is automatically
passed to the next iteration, and then the same loop body gets executed from the next round in
usual manner.
for(int i=0;i<=5;i++){

if(i==3)

continue;

System.out.println(i);

18. break : break keyword is used to break out of a loop body or the switch block. The break
statement is used for early exiting from the loop or switch statement at specified conditions.

for(int i=0;i<=5;i++){

if(i==3)

break;

System.out.println(i);

19. goto ** : Not in use and has no function.

#4 Function Keywords

Keywords which are used basically with some functions.

20. void : void keyword is used to specify a method which does not return any value.

void main()

21. return : return keyword in Java is used to return back the control along with the value
from the called method(function) to the calling place.

int sum(int a, int b){

return a+b;

#5 Object Keywords

Java Keywords which are related to objects in Java program.


22. new : new keyword in Java is used to create the instance of a class by dynamically
allocating memory for a new object.

MyClass object = new MyClass();

23. this : this keyword in Java is used to refer to the current object inside a method or
constructor. It is also used to distinguish between the instance variable and local variable.

public class MyClass {

int a=50;

MyClass(int a){

this.a=a;

24. super : this keyword in Java is used to refer to the objects of the super class. It is used
when we want to call the super class variable, method and constructor through sub-class
object.

public class A {

int a =30;

class B extends A{

int a=40;

public void show(){

System.out.println(a);

System.out.println(super.a);

25. instanceof : instanceof keyword is used to check if the given object is an instantiated
object of the specified class or not. It returns the boolean value.
Test obj=new Test();

if(obj instanceof Test){

System.out.println("Yes");

else{

System.out.println("No");

#6 Access Specifier Keywords

Java Keywords which are related to specify the accessibility or scope of a field, method,
constructor or class.

26. public : public keyword in Java is used for classes, methods, variables and constructors,
which makes them accessible from anywhere.

public class test{}

27. private : private keyword in Java is used to specify that a method, constructor or
variable will be accessible only within the declared class.

private class test{}

28. protected : private keyword in Java is used to specify that a method, constructor or
variable will be accessible within the package and outside the package through inheritance
only.

protected class test{}

#7 Non-Access Modifier Keywords

Java keywords which do not have anything related to the level of access but they provide a
special functionality when specified.
29. final : final keyword in Java is used with variables, methods and classes. A final variable
is a constant value which cannot be changed. By making a method final, we cannot override
it. By making a class final, we cannot extend it.

final class Test1 //final class

final int value =10; //final variable

final void show(){} // final method

30. static : static keyword in Java is used with variables, methods, blocks and classes. The
static variables and methods get associated with the class as a whole rather than belonging to
the individual object. The static keyword is used with variables and methods to make them
constant for every instance of the class.

static int count; // static variable

public static void main(){} // static method

31. abstract : abstract keyword in Java is used to create abstract classes and abstract
methods. The abstract methods do not have the body of themselves and must be overridden in
all child classes. The class which contains an abstract method must be declared as an abstract
class using the abstract keyword, and we can not instantiate that class.

abstract class shape // abstract class

abstract double calculate(int x, int y); abstract method

32. synchronized : The synchronization keyword in Java is used to create a synchronization


block that allows only a single thread to access the shared data or resources at a particular
point of time. It specifies the critical sections or methods in multithreaded code.

synchronized void show(int num){}


33. transient : transient keyword in Java is used with instance variables to exclude them
from the serialization process. It cannot be used with the static keyword.

transient int value=12;

34. volatile : volatile keyword in Java is used to indicate the visibility of variables modified
by multiple threads during concurrent programming i.e every read or write of the volatile
variable will be to the main memory and not the CPU cache.

static volatile int value=12;

35. strictfp : strictfp keyword in Java is used to make floating-point calculations platform
independent.

Note : This keyword was added in JDK 1.2 version.

strictfp double calculate(){

double num1 = 10e+102;

double num2 = 6e+08;

return num1 + num2;

36. native : native keyword in Java is used to create a method native which indicates that the
method’s implementation is also written in different languages like C and C++ in native code
using JNI(Java Native Interface).

public native void test(){}

#8 Declarative Keywords

Java Keywords which are used to delcare something in Java progamming.

37. package : package keyword in Java is used to declare a Java package which includes
classes, sub-packages, and interfaces.

package mypackage;
38. import : import keyword in Java is used to make classes and interfaces inside a package
accessible to the current source code.

import javax.swing.JFrame;

39. class : class keyword in Java is used to declare a new class in Java.

class Test{}

40. interface : interface keyword in Java is used to declare an interface that only contains the
abstract methods.

interface myInterface{

abstract void show();

class Test implements myInterface {

public void show(){

System.out.println("Hello");

41. enum : enum keyword in Java is used to declare the enumerated(unchangeable) type,
which are fixed set of constants. The constructors of enum are always private or default.

Note : This keyword was added in JDK 5.0 version.

class Test{

enum WeekDays{

SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;
}

public static void main(String[] args){

System.out.println(WeekDays.MONDAY);

42. const** : Not in use and has no function.

#9 Inheritance Keywords

Java Keywords which are related to inheritance in Java programming

43. implements : implements keyword in Java is used to implement(kind of inheritance) an


interface in a class. The interface contains only abstract methods, and to access those
methods, another class must implement the interface using the implements keyword.

interface myInterface{

abstract void show();

class Test implements myInterface {

public void show(){

System.out.println("Hello");

44. extends : extends keyword in Java is used to inherit a new class from the base class
using inheritance.

class Base{

public void showFun(){

System.out.println("In base class");

}
}

class Child extends Base {

public void show(){

System.out.println("In child class");

#10 Exception Keywords

Java Keyword which are related with exception handling in Java programming

45. throw : throw keyword in Java is used to throw an exception explicitly from a method or
block of code. It is usually used with custom-made exceptions.

class Test{

int a=47;

int b=5;

void divide(){

if(b==5){

throw new ArithmeticException();

public static void main(String[] args){

Test test = new Test();

test.divide();

}
46. throws : throws keyword in Java is used to declare exceptions that can be thrown from a
method during the program execution.

void divide() throws ArithmeticException{

int a=12;

int b=0;

System.out.println(a/b);

47. try : try keyword in Java is used to create the try block, which is tested for any kind of
exceptions while it is being executed. A try block must be followed by either catch or finally
block.

try

int a=15;

int b=0;

System.out.println(a/b);

catch (ArithmeticException e)

System.out.println("Divide by zero Error");

48. catch : catch keyword in Java is used to create the catch block. When any exception
occurs in the try block, it is caught by the catch block and is only used after the try block.

try

int a=15;

int b=0;

System.out.println(a/b);
}

catch (ArithmeticException e)

System.out.println("Divide by zero Error");

49. finally : finally keyword in Java is used to create the finally block, which is used after
the try-catch block, and the finally block always gets executed whether an exception is found
or not.

finally

System.out.println("This block always gets executed whether exception is handled or not");

50. assert : assert keyword in Java is used to create an assertion(assumption), which is a


condition that should be true during the program execution. during runtime if the assertion is
false then an AssertionError is thrown.

Note : This keyword was added in JDK 1.4 version.

Data Types in Java


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.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared
before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

Current Time 0:00

Duration 0:00

 boolean data type


 byte data type
 char data type
 short data type
 int data type
 long data type
 float data type
 double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:
1. Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used
in place of "int" data type.

Example:

1. byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767.
Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.

Example:

1. short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.

Example:

1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example:

1. char letterA = 'A'

Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest
range of Unicode system. To get detail explanation about Unicode visit next page.

You might also like