0% found this document useful (0 votes)
7 views52 pages

JAVA-CS270-UNIT-1&2

Uploaded by

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

JAVA-CS270-UNIT-1&2

Uploaded by

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

UNIT-1

Definition of Programming

In computer science fields, the word program characterizes what a computer


actually does and this process is known as programming.

We can also define the term programming as it is the process that models
or structure the set of instructions that instruct the machine how to perform
a task and what to perform. It can be done using a variety of programming
languages such as C, C++, C#, Python, Java, etc.

Advantages of Programming

o It enhances problem-solving skills.


o Using programming, we can solve complex problems.
o It is also learning with fun.
o It can perform multiple tasks can be bundled into one module.
o It saves time and effort.

Programming Paradigms

In layman's terms, programming paradigms are a fundamental style of


computer programming.

In technical terms, a programming paradigm is a way to deal with tackle


issues utilizing some programming language. Additionally, we can say that
it is a strategy to take care of an issue using tools and techniques that are
accessible to us following some methodology.

It differs in the concepts and methods that are used to represent the elements
(such as objects, variables, functions, and constraints) of a program. And
the steps that involve a calculation (like assignations, evaluation,
continuations, and data flows). The lowest programming paradigm
is machine code.
There are lots of things for programming languages that are known.
However, every one of them needs to follow some procedure when they are
executed and this approach/methodology is a paradigm.

Types of Programming Paradigms

There is the following two programming paradigm:

o Imperative Programming Paradigm


o Declarative Programming Paradigm

Imperative Programming Paradigm

Imperative programming is a programming paradigm that uses statements


that change a program's state. An imperative program consists of commands
for the computer to perform. It describes the detail of how the results are to
be obtained. How means describing the inputs and describing how the
outputs are produced.

Examples of imperative programming paradigm are C, Fortran, Basic, Java,


C++, Python, Ruby, PHP, etc.

Declarative Programming Paradigm

Declarative programming is a style of building the structure and elements of


computer programs. It expresses the logic of a computation without
describing its control flow. In other words, styles of programming that are
not imperative are called declarative programming paradigm. It
emphasizes what the program should accomplish.

Examples of declarative programming paradigm are Scala, Haskell, Erlang,


Lisp, ML, Closure, SQL, XSQL, etc.
Computer Programming Hierarchy

A programming language is an artificial language that can control the


behaviour of a machine, specifically in computers. Programming language
like natural languages is defined by syntactic and semantic rules which
define their structure and meaning respectively. The hierarchical structure of
programming languages is as follows −
Values − In computer science, a value is a sequence of bits that is
interpreted according to various data types. The same sequence of bits can
have several values, depending on the type can interpret its meaning. For
instance, the value can be an integer or floating-point value, or string.

Variable − In computer programming, a variable is an identifier (generally a


letter, word, or phrase) that is connected to a value saved in the system’s
memory or an expression that can be computed.
Operator − Programming languages generally provide a set of operators
that are equivalent to operators in mathematics. A language can include a
fixed number of built-in operators such as +,-,*, = in C and C++.

Features of Java

The primary objective of Java programming language creation was to make


it portable, simple and secure programming language. Apart from this, there
are also some excellent features which play an important role in the
popularity of this language. The features of Java are also known as Java
buzzwords.

A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it


after C++).
o Java has removed many complicated and rarely-used features, for
example, explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an


object. Object-oriented means we organize our software as a combination of
different types of objects that incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies


software development and maintenance by providing some rules.

Basic concepts of OOPs are:


1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Secured

Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because

JVM (Java Virtual Machine) Architecture

. Java Virtual Machine


. Internal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified.


But implementation provider is independent to choose the algorithm.
Its implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java
Runtime Environment).
3. Runtime Instance Whenever you write java command on the
command prompt to run the java class, an instance of JVM is created.

What it does
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
What is Java Bytecode?

Java bytecode is the instruction set for the Java Virtual Machine. It acts
similar to an assembler which is an alias representation of a C++ code. As
soon as a java program is compiled, java bytecode is generated. In more apt
terms, java bytecode is the machine code in the form of a .class file. With
the help of java bytecode we achieve platform independence in java.

Install Java

Step 1: Verify that it is already installed or not

Check whether Java is already installed on the system or not. In my case, it


is not installed therefore I need to install JDK 1.8 on my computer.

Step 2: Download JDK

Click the below link to download jdk 1.8 for you windows 64 bit system.

Download JDK For Windows


There are available releases for Linux and mac operating systems. You can
visit the official link for JDK distributions i.e.

DK Downloads

Step 3: Install JDK

Open the executable file which you have just downloaded and follow the
steps.

Click Next to continue


Just Choose Development Tools and click Next.
Set up is being ready.
Choose the Destination folder in which you want to install JDK. Click Next
to continue with the installation.
Set up is installing Java to the computer.
We have successfully installed Java SE development kit 8. Close the
installation set up.

Step 4 : Set the Permanent Path

To execute Java applications from command line, we need to set Java Path.
To set the path, follow the following steps.
Right click on "this PC". It can be named as "My Computer" in some
systems. Choose "properties" from the options.
The screen look alike the above image will open. Click on "Advanced
system settings" to continue.
Above window will open. Click on "Environment Variables" to continue.

Enter "path" in variable name and enter the path to the bin folder inside your
JDK in the variable value. Click OK.
Now Java Path has been set up. Open the Command prompt and
type "javac" In case you have already open up the command prompt, I
suggest you to close the existing window and reopen it again.

We will get javac executed as shown in the image below.

The Java has been installed on our system. Now, we need to configure IDEs
like NetBeans or Eclipse in order to execute JavaFX applications.
What is Java?

Java is a programming language and a platform. Java is a high level,


robust, object-oriented and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of


Oracle) in the year 1995. James Gosling is known as the father of Java.
Before Java, its name was Oak. Since Oak was already a registered company,
so James Gosling and his team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs,


is known as a platform. Since Java has a runtime environment (JRE) and
API, it is called a platform.

Java Example

Let's have a quick look at Java programming example. A detailed


description of Hello Java example is available in next page.

Simple.java

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Test it Now

Application

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.

Java File Class

The File class is an abstract representation of file and directory pathname. A


pathname can be either absolute or relative.

The File class have several methods for working with directories and files
such as creating new directories or files, deleting and renaming directories or
files, listing the contents of a directory etc.

the Java programming language, we can develop a wide variety of


applications. So, before diving in depth, it is necessary to understand
the basic structure of Java program in detail. In this section, we have
discussed the basic structure of a Java program. At the end of this section,
you will able to develop the Hello world Java program, easily.

Let's see which elements are included in the structure of a Java program. A
typical structure of a Java program contains the following elements:

o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors
Documentation Section

The documentation section is an important section but optional for a Java


program. It includes basic information about a Java program. The
information includes the author's name, date of creation, version,
program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the
documentation section, the Java compiler ignores the statements during the
execution of the program. To write the statements in the documentation
section, we use comments. The comments may be single-line,
multi-line, and documentation comments.

o Single-line Comment: It starts with a pair of forwarding slash (//).


For example:

1. //First Java Program


o Multi-line Comment: It starts with a /* and ends with */. We write
between these two symbols. For example:

1. /*It is an example of
2. multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends
with */. For example:

1. /**It is an example of documentation comment*/


How to Compile and Run Java Program

In this section, we learn how to compile and run java program step by step.

Step 1:
Write a program on the notepad and save it with .java (for example,
DemoFile.java) extension.

1. class DemoFile
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Hello!");
6. System.out.println("Java");
7. }
8. }

Step 2:

Open Command Prompt.

Step 3:

Set the directory in which the .java file is saved. In our case, the .java file is
saved in C:\\demo.

Step 4:

Use the following command to compile the Java program. It generates


a .class file in the same folder. It also shows an error if any.
1. javac DemoFile.java

Step 5:

Use the following command to run the Java program:

1. java DemoFile

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
3. Just-In-Time Compiler

tokens.

A lexical token may consist of one or more characters, and every single
character is in exactly one token.

The tokens can be keywords, comments, numbers, white space, or strings.


All lines should be terminated by a semi-colon (;)

o Verilog HDL is a case-sensitive language.


o And all keywords are in lowercase.

White Space

White space can contain the characters for tabs, blanks, newlines, and form
feeds. These characters are ignored except when they serve to separate other
tokens. However, blanks and tabs are significant in strings.

Comments

There are two types to represent the comments, such as:

1. Single line comments begin with the token // and end with a carriage
return.
For example, //this is the single-line syntax.
2. Multi-Line comments begin with the token /* and end with the token
*/
For example, /* this is multiline syntax*/
Identifiers in Java

Identifiers in Java are symbolic names used for identification. They can be a
class name, variable name, method name, package name, constant name, and
more. However, In Java, There are some reserved words that can not be used
as an identifier.

For every identifier there are some conventions that should be used before
declaring them. Let's understand it with a simple Java program:

1. public class HelloJava {


2. public static void main(String[] args) {
3. System.out.println("Hello JavaTpoint");
4. }
5. }

From the above example, we have the following Java identifiers:

1. HelloJava (Class name)


2. main (main method)
3. String (Predefined Class name)
4. args (String variables)
5. System (Predefined class)
6. out (Variable name)
7. println (method)

What are keywords in Java?

In Java, a keyword is a reserved word that conveys a specific meaning to the


Java compiler. Keywords are special words that have a predefined meaning
to the Java compiler. They are reserved words and cannot be used as an
identifier, function names, class names, etc in a programming language.

Literals in Java

In Java, literal is a notation that represents a fixed value in the source code.
In lexical analysis, literals of a given type are generally known as tokens. In
this section, we will discuss the term literals in Java.

Literals

In Java, literals are the constant values that appear directly in the program. It
can be assigned directly to a variable. Java has various types of literals. The
following figure represents a literal.

Types of Literals in Java

There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

Java Comments

Comments can be used to explain Java code, and to make it more readable.
It can also be used to prevent execution when testing alternative code.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be
executed).

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.

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
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:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Which are assignment operators?

The assignment operator = assigns the value of its right-hand operand to a


variable, a property, or an indexer element given by its left-hand operand.
The result of an assignment expression is the value assigned to the left-hand
operand.
UNIT-2

Class Definition in Java


In object-oriented programming, a class is a basic building block. It can be defined
as template that describes the data and behaviour associated with the class
instantiation. Instantiating is a class is to create an object (variable) of that class
that can be used to access the member variables and methods of the class.

A class can also be called a logical template to create the objects that share
common properties and methods.

For example, an Employee class may contain all the employee details in the form
of variables and methods. If the class is instantiated i.e. if an object of the class is
created (say e1), we can access all the methods or properties of the class.

Java Class Example

Example 1:

Let's consider the following example to understand how to define a class in Java
and implement it with the object of class.

Calculate.java

1. // class definition
2. public class Calculate {
3.
4. // instance variables
5. int a;
6. int b;
7.
8. // constructor to instantiate
9. public Calculate (int x, int y) {
10. this.a = x;
11. this.b = y;
12. }
13.
14. // method to add numbers
15. public int add () {
16. int res = a + b;
17. return res;
18. }
19.
20. // method to subtract numbers
21. public int subtract () {
22. int res = a - b;
23. return res;
24. }
25.
26. // method to multiply numbers
27. public int multiply () {
28. int res = a * b;
29. return res;
30. }
31.
32. // method to divide numbers
33. public int divide () {
34. int res = a / b;
35. return res;
36. }
37.
38.
39. // main method
40. public static void main(String[] args) {
41. // creating object of Class
42. Calculate c1 = new Calculate(45, 4);
43.
44. // calling the methods of Calculate class
45. System.out.println("Addition is :" + c1.add());
46. System.out.println("Subtraction is :" + c1.subtract());
47. System.out.println("Multiplication is :" + c1.multiply());
48. System.out.println("Division is :" + c1.divide());
49.
50.
51. }

Output:

Object Definition in Java


Objects are key to understanding object-oriented technology. The purpose of the
object-oriented programming is to implement the real word entities in
programming. It also emphasis on the binding of data. There are various OOPs
concepts among them Object is one of them. In this section, we will discuss the
object definition in Java.
Object Definition

In object-oriented programming terminology, an object is a member of Java class.


It is also known as instance of the class. Note that objects are created at run time.
In simple words, object is a real word entity. For example, dog, car, pen, desk, etc.
Each object shares the following two characteristics:

o Identity:Object identity is a unique ID. The value of the ID is not visible to


the external user. It is used internally by the JVM to identify each object
uniquely.
o State: The state of an object stored in variables (fields).
o Behavior: The methods shows the behavior of an object.

Using Object in a Java Program

Student.java

1. public class Employee


2. {
3. int stu_id=105; // data member (or instance variable)
4. String stu_name="Nitin"; // data member (or instance variable)
5. public static void main(String args[])
6. {
7. // Creating an object of the Student class
8. Student stu = new Student();
9. System.out.println("Student ID: "+e.stu_id);
10. System.out.println("Student Name: "+e.stu_name);
11. }
12. }

Output:

Student Id: 105


Student Name: Nitin

Difference between object and class


There are many differences between object and class. A list of differences between
object and class are given below:

No. Object Class

1) Object is an instance of a class. Class is a blueprint or


template from which
objects are created.

2) Object is a real world entity such as pen, laptop, Class is a group of


mobile, bed, keyboard, mouse, chair etc. similar objects.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new keyword mainly Class is declared


e.g. using class
Student s1=new Student(); keyword e.g.
class Student{}

5) Object is created many times as per requirement. Class is declared once.

6) Object allocates memory when it is created. Class doesn't allocated


memory when it is
created.

7) There are many ways to create object in java There is only one way
such as new keyword, newInstance() method, to define class in java
clone() method, factory method and using class keyword.
deserialization.

Let's see some real life example of class and object in java to understand the
difference well:

Class: Human Object: Man, Woman


Class: Fruit Object: Apple, Banana, Mango, Guava wtc.

Class: Mobile phone Object: iPhone, Samsung, Moto

Class: Food Object: Pizza, Burger, Samosa

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory


automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes the


unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.

How to Create Object in Java

The object is a basic building block of an OOPs language. In Java, we cannot


execute any program without creating an object. There is various way to create
an object in Java that we will discuss in this section, and also learn how to create
an object in Java.

Java provides five ways to create an object.


o Using new Keyword
o Using clone() method
o Using newInstance() method of the Class class
o Using newInstance() method of the Constructor class
o Using Deserialization

Using new Keyword

Using the new keyword is the most popular way to create an object or instance of
the class. When we create an instance of the class by using the new keyword, it
allocates memory (heap) for the newly created object and also returns
the reference of that object to that memory. The new keyword is also used to
create an array. The syntax for creating an object is:

1. ClassName object = new ClassName();

Let's create a program that uses new keyword to create an object.

CreateObjectExample1.java

1. public class CreateObjectExample1


2. {
3. void show()
4. {
5. System.out.println("Welcome to javaTpoint");
6. }
7. public static void main(String[] args)
8. {
9. //creating an object using new keyword
10. CreateObjectExample1 obj = new CreateObjectExample1();
11. //invoking method using the object
12. obj.show();
13. }
14. }

Output:

Welcome to javaTpoint

By using the new keyword, we can also invoke the constructor (default or
parametrized) of the class.

Constructors in Java

. Types of constructors
. Default Constructor
. Parameterized Constructor
. Constructor Overloading
. Does constructor return any value?
. Copying the values of one object into another
. Does constructor perform other tasks instead of the initialization

In Java, a constructor is a block of codes similar to the method. It is called when


an instance of the class is created. At the time of calling constructor, memory for
the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor
is called.

It calls a default constructor if there is no constructor available in the class. In such


case, Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Access Modifiers in Java


. Private access modifier
. Role of private constructor
. Default access modifier
. Protected access modifier
. Public access modifier
. Access Modifier with Method Overriding

There are two types of modifiers in Java: access modifiers and non-access
modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Nesting Of Methods in Java
In Java, methods and variables that are defined within a class can only be accessed
by creating an instance of that class or by using the class name if the methods are
static. The dot operator is used to access methods and variables within a class.
However, there is an exception to this rule: a method can also be called by another
method using the class name, but only if both methods are present in the same
class. Efficient code organization and simplified method calls within a class are
possible through nesting of methods. Understanding how methods can call other
methods within the same class is an important aspect of Java programming.

Syntax:

1. class Main
2. {
3. method1(){
4.
5. // statements
6. }
7.
8. method2()
9. {
10. // statements
11.
12. // calling method1() from method2()
13. method1();
14. }
15. method3()
16. {
17. // statements
18.
19. // calling of method2() from method3()
20. method2();
21. }
22. }

Java Anonymous inner class


Java anonymous inner class is an inner class without a name and for which only a
single object is created. An anonymous inner class can be useful when making an
instance of an object with certain "extras" such as overloading methods of a class
or interface, without having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in
Java. It should be used if you have to override a method of class or interface. Java
Anonymous inner class can be created in two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class

TestAnonymousInner.java

1. abstract class Person{


2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }
Test it Now

Output:

nice fruits

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be
instantiated.

But there are many differences between abstract class and interface that are given
below.

Abstract class Interface

1) Abstract class can have abstract Interface can have only


and non-abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend An interface can extend another Java


another Java class and implement interface only.
multiple Java interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface


achieves fully abstraction (100%).

Java Command Line Arguments


. Command Line Argument
. Simple example of command-line argument
. Example of command-line argument that prints all the values

The java command-line argument is an argument i.e. passed at the time of running
the java program.

The arguments passed from the console can be received in the java program and it
can be used as an input.

So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.

Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this
java program, you must pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }

1. compile by > javac CommandLineExample.java


2. run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

Method Overloading in Java


. Different ways to overload the method
. By changing the no. of arguments
. By changing the datatype
. Why method overloading is not possible by changing the return type
. Can we overload the main method
. method overloading with Type Promotion

If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as
other programmers to understand the behavior of the method because its name
differs.
So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Recursion in Java

Recursion in java is a process in which a method calls itself continuously. A


method in java that calls itself is called recursive method.

It makes the code compact but complex to understand.

Syntax:

1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }

Java Recursion Example 1: Infinite times

1. public class RecursionExample1 {


2. static void p(){
3. System.out.println("hello");
4. p();
5. }
6.
7. public static void main(String[] args) {
8. p();
9. }
10. }

Output:

hello
hello
...
java.lang.StackOverflowError

Java static keyword


. Static variable
. Program of the counter without static variable
. Program of the counter with static variable
. Static method
. Restrictions for the static method
. Why is the main method static?
. Static block
. Can we execute a program without main method?
The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The static
keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable

If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.
Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";

Java Object finalize() Method


Finalize() is the method of Object class. This method is called just before an object
is garbage collected. finalize() method overrides to dispose system resources,
perform clean-up activities and minimize memory leaks.

Syntax

1. protected void finalize() throws Throwable

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
Usage of Java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usages of this keyword.

You might also like