Java Programming
Java Programming
GROUP ASSIGNMENT BY
ASSIGNMENT TOPIC:
JAVA PROGRAMMING LANGUAGE
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing
someconcepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example:
chair, pen, table, keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because allthe data members are private here.
Benefits of Inheritance
• One of the key benefits of inheritance is to minimize the amount of duplicate code
equivalent code exists in two related classes, the hierarchy can usually be
refactored to move the common code up to a mutual superclass. This also tends to
• Inheritance can also make application code more flexible to change because
• Extensibility - extending the base class logic as per business logic of the derivedclass.
•
• Data hiding - base class can decide to keep some data private so that it cannot be altered
by the derived class
The history of java starts from Green Team. Java team members (also known as
Green Team), initiated a revolutionary task to develop a language for digital devices
such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But it was suited
for internet programming. Later, Java technology as incorporated by Netscape.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set- top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was.gt.
4) After that, it was called Oak and was developed as a part of the Green
project.
Java Version History
There are many java versions that has been released. Current stable release of Java is
Java SE 8.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High-performance
11. Multithreaded
12. Distributed
Java Comments
The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about the
variable, method, class or any statement. It can also be used to hide program code for
specific time.
Example:
Output:
10
Syntax:
/* Thisis
multi linecomment
*/
Example:
Output:
10
Syntax:
/** This is
documentation comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2
numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}
javac Calculator.java
javadoc Calculator.java
Now, there will be HTML files created for your Calculator class in the current directory.
Open the HTML files and see the explanation of Calculator class provided through
documentation comment.
Data types represent the different values to be stored in the variable. In java, there are
two types of data types:
o Primitive datatypes
o Non-primitive datatypes
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Output:20
Variable is a name of memory location. There are three types of variables in java: local,
instanceand static. There are two types of data types in java: primitive and non-primitive.
Types of Variable
There are three types of variables in java:
o localvariable
o instancevariable
o staticvariable
1) LocalVariable
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance
variable. Itis not declared as static.
3) Staticvariable
A variable that is declared as static is called static variable. It cannot be local.We will have
detailed learning of these variables in next chapters.
Example to understand the types of variables in java
class A{
int data=50;//instance variable static int m=100;//static variable void method(){
int n=90;//local variable
}
}//end of class
A constant is a variable which cannot have its value changed after declaration. It uses the
'final' keyword.
Syntax
modifierfinal dataType variableName = value; //global constant
Instance variables
Instance variables are those that are defined within a class itself and not in any method
or constructor of the class. They are known as instance variables because every instance
of the class (object) contains a copy of these variables. The scope of instance variables is
determined by the access specifier that is applied to these variables. We have already
seen about it earlier. The lifetime of these variables is the same as the lifetime of the
object to which it belongs. Object once created do not exist for ever. They are destroyed
by the garbage collector of Java when there are no more reference to that object. We
shall see about Java's automatic garbage collector later on.
Argument variables
These are the variables that are defined in the header oaf constructor or a method. The
scope of these variables is the method or constructor in which they are defined. The
lifetime is limited to the time for which the method keeps executing. Once the method
finishes execution, these variables are destroyed.
Local variables
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access specifiers
can be applied to instance variables only and not to argument or local variables.
Operators In Java
Operators Hierarchy
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types
ofexpressions in Java:
• Those that have no result but might have a "side effect" because an expression can
include a wide range of elements such as method invocations or increment operators that
modify the state (i.e. memory) of aprogram.
Java Type casting and Type conversion
For Example, in java the numeric data types are compatible with each other but no
automatic conversion is supported from numeric type to char or boolean. Also, char and
boolean are not compatible with each other.
The control flow statements in Java allow you to run or skip blocks of code when
specialconditions are met.
The “if” Statement
The “if” statement in Java works exactly like in most programming languages. With the
help of“if” you can choose to execute a specific block of code when a predefined
condition is met. Thestructure of the “if” statement in Java looks like this:
if(condition) {
// execute this code
The condition is Boolean. Boolean means it may be true or false. For example you may put
amathematical equation as condition. Look at this full example:
1. Write a main method that runs your program. You can write this method
anywhere. In this example, I'll write my main method in a class called Main that has no
other methods. For example:
2. public class Main
3. {
4. public static void main(String[] args)5. {
6. Game.play();
7. } }
8. Make sure your code is compiled, and that you have tested it thoroughly.
9. If you're using Windows, you will need to set your path to include Java, if you
haven't done so already. This is a delicate operation. Open Explorer, and look inside
C:\ProgramFiles\Java, and you should see some version of the JDK. Open this folder, and
then open the bin folder. Select the complete path from the top of the Explorer window,
and press Ctrl-C to copy it.
Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and
select properties. Click on the Advanced tab, and then click on the Environment variables
button. Look at the variables listed for all users, and click on the Path variable. Do not
delete the contents of this variable! Instead, edit the contents by moving the cursor to
the right end, entering a semicolon (;), and pressing Ctrl-V to paste the path you copied
earlier. Then go ahead and save your changes. (If you have any Cmd windows open, you
will need to close them.)
10. If you're using Windows, go to the Start menu and type "cmd" to run a program
that brings up a command prompt window. If you're using a Mac or Linux machine, run
the Terminal program to bring up a command prompt.
11. In Windows, type dir at the command prompt to list the contents of the current
directory. On a Mac or Linux machine, type ls to do this.
Java -Methods
A Java method is a collection of statements that are grouped together to perform an
operation. When you call the System.out.println() method, for example, the system
actually executes several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke
amethod with or without parameters, and apply method abstraction in the program
design.
Creating Method
Considering the following example to explain the syntax of a method −
Here,
• int − returntype
• a, b − formalparameters
Method definition consists of a method header and a method body. The same is shown in
thefollowing syntax −
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
• modifier− It defines the access type of the method and it is optional touse.
• nameOfMethod− This is the method name. The method signature consists of themethod
name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of parameters
of a method. These are optional, method may contain zeroparameters.
• method body − The method body defines what the method does with thestatements.
The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the classthan instance of the class.
3. block
4. nestedclass
o The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of studentsetc.
o The static variable gets memory only once in class area at the time of classloading.
2. introllno;
3. Stringname;
4. String college="ITS";
5.}
String name;
staticString college ="ITS"; Student8(int r,String n){ rollno =r;
name =n;
}voiddisplay (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){ Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}}
Output:111 KaranITS
222 AryanITS
If you apply static keyword with any method, it is known as static method.
1) It doesn't block the user because threads are independent and you can
performmultiple operations at sametime.
A thread can be in one of the five states. According to sun, there is only 4 states in
thread lifecycle in java
new, runnable, non-runnable and terminated. There is no running state. But for better
understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated
How to create thread
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class: