Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Java Programming

The document is a group assignment on Java Programming Language, detailing Object-Oriented Programming (OOP) concepts such as inheritance, polymorphism, abstraction, and encapsulation. It covers the history of Java, its features, comments, data types, variables, operators, expressions, type casting, and control flow statements. Additionally, it provides examples and explanations of Java syntax and application creation.

Uploaded by

emmanuelokeke804
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Programming

The document is a group assignment on Java Programming Language, detailing Object-Oriented Programming (OOP) concepts such as inheritance, polymorphism, abstraction, and encapsulation. It covers the history of Java, its features, comments, data types, variables, operators, expressions, type casting, and control flow statements. Additionally, it provides examples and explanations of Java syntax and application creation.

Uploaded by

emmanuelokeke804
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

ALVAN IKOKU FEDERAL UNIVERSITY OF EDUCATION, OWERRI

IN AFFILIATION WITH UNIVERSITY OF NIGERIA, NSUKKA (UNN)

GROUP ASSIGNMENT BY

NAME: REG. NO:


OKORO CHIDINMA AUGUSTINA BD/20/13/91430
IZUORA GLORIA CHIAMAKA BD/20/13/92122

COURSE CODE: CRE 427


COURSE TITLE PROGRAMMING LANGUAGE
DEPARTMENT: COMPUTER EDUCATION
LEVEL: 4/4 DEGREE

LECTURER: MRS. NGOZI

ASSIGNMENT TOPIC:
JAVA PROGRAMMING LANGUAGE

JAVA PROGRAMMING Page 1


OOPs Concepts
Object Oriented Programming is a paradigm that provides many concepts such as
inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming


paradigm where everything is represented as an object is known as truly object-oriented
programming language.

Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)

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

Collection of objects is called class. It is a logical entity.

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.

JAVA PROGRAMMING Page 2


Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or rectangle
etc.
In java, we use method overloading and method overriding to achieve polymorphism.Another
example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

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

in an application by sharing common code amongst several subclasses. Where

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

result in a better organization of code and smaller, simpler compilationunits.

• Inheritance can also make application code more flexible to change because

classesthat inherit from a common superclass can be used interchangeably. If

the return type of a method issuperclass


• Reusability - facility to use public methods of base class without rewriting thesame.

• 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

JAVA PROGRAMMING Page 3


Procedural and object-oriented programming paradigms

JAVA PROGRAMMING Page 4


Java Programming
History Of Java

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.

Currently, Java is used in internet programming, mobile devices, games, e-business


solutions etc. There are given the major points that describes the history of java.

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. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep,2004)
8. Java SE 6 (11th Dec,2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March,2014)

JAVA PROGRAMMING Page 5


Features of Java
There is given many features of java. They are also known as java buzzwords. The Java
Features given below are simple and easy to understand.

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.

Types of Java Comments


There are 3 types of comments in java.

1. Single Line Comment


2. Multi line Comment
3. Documentation Comment

Java Single Line Comment

The single line comment is used to comment only one line.

JAVA PROGRAMMING Page 6


Syntax:

1. //This is single line comment

Example:

public class CommentExample1 {


public static void main(String[] args) { int i=10;//Here, i is a variable
System.out.println(i);
}
}

Output:

10

Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

/* Thisis
multi linecomment
*/

Example:

public class CommentExample2 {


public static void main(String[] args) {
/* Let's declare and print variable in java.*/
inti=10; System.out.println(i);
}}

Output:

10

JAVA PROGRAMMING Page 7


Java Documentation Comment

The documentation comment is used to create documentation API. To create


documentation API, you need to use javadoc tool.

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;}
}

Compile it by javac tool:

javac Calculator.java

Create Documentation API by javadoc tool:

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.

JAVA PROGRAMMING Page 8


Data Types

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

DataT DefaultValu Default


ype e size

boolea False 1 bit


n

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

JAVA PROGRAMMING Page 9


double 0.0d 8 byte

Java Variable Example: Add Two Numbers


class Simple{
public static void main(String[] args){
int a=10; int b=10; int c=a+b;
System.out.println(c);
}}

Output:20

Variables and Data Types in Java

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

A variable which is declared inside the method is called local variable.

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

JAVA PROGRAMMING Page 10


Constants in Java

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

modifierstatic final dataType variableName = value; //constant within a c

Scope and Life Time of Variables


The scope of a variable defines the section of the code in which the variable is visible. As
a general rule, variables that are defined within a block are not accessible outside that
block. The lifetime of a variable refers to how long the variable exists before it
isdestroyed. Destroying variables refers to deallocating the memory that was allotted to
the variables when declaring it. We have written a few classes till now. You might have
observed that not all variables are the same. The ones declared in the body of a method
were different from those that were declared in the class itself. There are three types of
variables: instance variables, formal parameters or local variables and localvariables.

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.

JAVA PROGRAMMING Page 11


In addition to the local variables defined in a method, we also have variables that are
defined in bocks life an if block and an else block. The scope and is the same as that of
the block itself.

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.

Operators Hierarchy

JAVA PROGRAMMING Page 12


Expressions
Expressions are essential building blocks of any Java program, usually created to produce
a newvalue, although sometimes an expression simply assigns a value to a variable.
Expressions are built using values, variables, operators and method calls.

Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three types
ofexpressions in Java:

• Those that produce a value, i.e. the result of (1 + 1)

• Those that assign a variable, for example (v =10)

• 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

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically converted. This
happenswhen:
▪ The two data types arecompatible.
▪ When we assign value of a smaller data type to a bigger datatype.

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.

Narrowing or Explicit Conversion


If we want to assign a value of larger data type to a smaller data type we perform
explicit type casting or narrowing.
▪ This is useful for incompatible data types where automatic conversion cannot bedone.
▪ Here, target-type specifies the desired type to convert the specified valueto.

JAVA PROGRAMMING Page 13


Control Flow Statements

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:

JAVA PROGRAMMING Page 14


Creating a Stand-Alone Java Application

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 −

JAVA PROGRAMMING Page 15


Syntax

public static int methodName(int a, int b) {


// body
}

Here,

• public static −modifier

• int − returntype

• methodName − name of the method

• a, b − formalparameters

• int a, int b − list ofparameters

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
}

The syntax shown above includes −

• modifier− It defines the access type of the method and it is optional touse.

• returnType− Method may return avalue.

• 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.

JAVA PROGRAMMING Page 16


Static Fields and Methods

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.

The static can be:

1. variable (also known as classvariable)

2. method (also known as classmethod)

3. block

4. nestedclass

Java static variable

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

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.

Advantage of static variable

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

Understanding problem without static variable


1. classStudent{

2. introllno;
3. Stringname;
4. String college="ITS";
5.}

Example of static variable


//Program of static variable
classStudent8{ introllno;

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

Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than object of aclass.


o A static method can be invoked without the need for creating an instance of aclass.
o static method can access static data member and can change the value ofit.

Example of static method


//Program of changing the common property of all objects(static field).

classStudent9{ int rollno; String name;


staticString college = "ITS"; static void change(){ college = "BBDIT";
}
Student9(int r, String n){rollno =r; name =n;
}
voiddisplay (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){ Student9.change();
Student9 s1 = new Student9 (111,"Karan"); Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo"); s1.display();
s2.display();
s3.display();
}}
Output:111 Karan BBDIT222 Aryan BBDIT
333 Sonoo BBDIT
Multithreading

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can
performmultiple operations at sametime.

2) You can perform many operations together so it savestime.

3) Threads are independent so it doesn't affect other threads if exception occur in a


singlethread.

Life cycle of a Thread (Thread States)

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

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

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:

oThread() oThread(String name)oThread(Runnable r)


oThread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for athread.


2. public void start(): starts the execution of the thread.JVM calls the run() method
onthethread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number ofmilliseconds.
4. public void join(): waits for a thread todie.
5. public void join(long miliseconds): waits for a thread to die for the
specifiedmiliseconds.
6. public int getPriority(): returns the priority of thethread.
7. public int setPriority(int priority): changes the priority of thethread.
8. public String getName(): returns the name of thethread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executingthread.
11. public int getId(): returns the id of thethread.
12. public Thread.State getState(): returns the state of thethread.
13. public boolean isAlive(): tests if the thread isalive.
14. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads toexecute.
15. public void suspend(): is used to suspend thethread(depricated).
16. public void resume(): is used to resume the suspendedthread(depricated).
17. public void stop(): is used to stop thethread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemonthread.
19. public void setDaemon(boolean b): marks the thread as daemon or userthread.
20. public void interrupt(): interrupts thethread.
21. public boolean isInterrupted(): tests if the thread has beeninterrupted.
22. public static boolean interrupted(): tests if the current thread has beeninterrupted.

You might also like