Wednesday, 31 October 2018

MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
1.1 Introduction
Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++.
Java is created by James Gosling from Sun Microsystems (Sun) in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.
Java is defined by a specification and consists of a programming language, a compiler, core libraries and a runtime machine(Java virtual machine).
The Java runtime allows software developers to write program code in other languages than the Java programming language which still runs on the Java virtual machine.
The Java platform is usually associated with the Java virtual machine and the Java core libraries.
Java virtual machine
The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.
Java Runtime Environment vs. Java Development Kit
A Java distribution typically comes in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK).
The JRE consists of the JVM and the Java class libraries. Those contain the necessary functionality to start Java programs.
The JDK additionally contains the development tools necessary to create Java programs. The JDK therefore consists of a Java compiler, the Java virtual machine and the Java class libraries.
Uses of JAVA
Java is also used as the programming language for many different software programs, games, and add-ons.
Some examples of the more widely used programs written in Java or that use Java include the Android apps, Big Data Technologies, Adobe Creative suite, Eclipse, Lotus Notes, Minecraft, OpenOffice, Runescape, and Vuze.
1.2 Features
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
1. Simple
Java is easy to learn and its syntax is quite simple and easy to understand.
2. Object-Oriented
In java everything is Object which has some data and behaviour. Java can be easily extended as it is based on Object Model.
3. Platform independent
Unlike other programming languages such as C, C++ etc which are compiled into platform specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent and can be run on any machine, plus this bytecode format also provide security. Any machine with Java Runtime Environment can run Java Programs.
4. Secured
When it comes to security, Java is always the first choice. With java secure features it enable us to develop virus free, temper free system. Java program always runs in Java runtime environment with almost null interaction with system OS, hence it is more secure.
5. Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error checking and runtime checking. But the main areas which Java improved were Memory Management and mishandled Exceptions by introducing automatic Garbage Collector and Exception Handling.
6. Architecture neutral
Compiler generates bytecodes, which have nothing to do with a particular computer architecture, hence a Java program is easy to intrepret on any machine.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
7. Portable
Java Bytecode can be carried to any platform. No implementation dependent features. Everything related to storage is predefined, example: size of primitive data types
8. High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++. But, Java enables high performance with the use of just-in-time compiler.
9. Multithreaded
Java multithreading feature makes it possible to write program that can do many tasks simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to execute multiple threads at the same time, like While typing, grammatical errors are checked along.
10. Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.
11. Interpreted
An interpreter is needed in order to run Java programs. The programs are compiled into Java Virtual Machine code called bytecode. The bytecode is machine independent and is able to run on any machine that has a Java interpreter. With Java, the program need only be compiled once, and the bytecode generated by the Java compiler can run on any platform.
1.3 Pros and Cons
Pros :
1. Java is Simple
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
2. Java is object-oriented because programming in Java is centered on creating objects, manipulating objects, and making objects work together. This allows you to create modular programs and reusable code.
3. One of the most significant advantages of Java is Platform indenpendence.
4. Java is Secure: Java is one of the first programming languages to consider security as part of its design.
5. Java is Multithreaded: Multithreaded is the capability for a program to perform several tasks simultaneously within a program.
6. Java is Robust: Robust means reliable and no programming language can really assure reliability.
Cons:
1. Java can be perceived as significantly slower and more memory-consuming than natively compiled languages such as C or C++.
2. No local constants. In Java, variables that belong to a class can be made constant by declaring them to be final. Variables that are local to a method cannot be declared final, however.
3. Java is predominantly a single-paradigm language. However, with the addition of static imports in Java 5.0 the procedural paradigm is better accommodated than in earlier versions of Java.
2.1 Environment Setup
We need to install the Java Development Toolkit aka JDK, which is bundled with the Java Runtime Environment.
At this moment, the latest JDK versions is JDK 8.
All you have to do is head to the main download page provided by Oracle , and download the latest version that you will find.
Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Assuming you have installed Java in
c:\Program Files\java\jdk
1. Right-click on 'My Computer' and select 'Properties'.
2. Click on the 'Environment variables' button under the 'Advanced' tab.
3. Now, alter the 'Path' variable so that it also contains the path to the Java executable.
Example, if the path is currently set to
'C:\WINDOWS\SYSTEM32',
then change your path to read
'C:\WINDOWS\SYSTEM32; c:\Program Files\java\jdk\bin'.
Setting up the path for Linux, Ubuntu, UNIX, Solaris
Environment variable PATH should be set to point to where the Java binaries have been installed.
Refer to your shell documentation if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of your
'.bashrc: export PATH=/path/to/java:$PATH'
Up until now we have installed a variety of tools towards setting up our Java Development environment.
Since the JDK is already installed (from step one) we could actually jump to coding just by using our text editor of choice (NotePad++, TextPad, NotePad, Ultra Edit etc) and invoking the javac and java commands from the command line.
Free IDE for Java
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Netbeans: NetBeans IDE provides Java developers with all the tools needed to create professional desktop, mobile and enterprise applications.
Eclipse:Eclipse is another free Java IDE for developers and programmers and it is mostly written in Java. Eclipse lets you create various cross platform Java applications for use on mobile, web, desktop and enterprise domains.
2.2 First Program
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
save this file as Simple.java
To compile:javac Simple.java
To execute:java Simple
It will give output as Hello Java
Lets see what this is :
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visible to all.
static is a keyword, if we declare any method as static, it is known as static method. The main method is executed by the JVM, it doesn't require to create object to invoke the main method. So it saves memory.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
void is the return type of method, it means it doesn't return any value.
main is a entry point of the program. Execution of programs starts from main. It is called by Runtime System
String[] args is used for command line argument. We will learn it later.
System.out.println() is used print statement.
3.1 Variables
A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
You must declare all variables before they can be used.
The basic form of a variable declaration is shown here:
data_type variable = value;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c;
// Declares three ints, a, b, and c.
int a = 10, b = 10;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
// Example of initialization
double pi = 3.14159;
// declares and assigns a value of PI.
char a = 'a';
// the char variable a iis initialized with value 'a'
Constant: During the execution of program, value of variable may change. A constant represents permanent data that never changes.
If you want use some value likes p=3.14159; no need to type every time instead you can simply define constant for p, following is the syntax for declaring constant.
Static final datatype ConstantName = value;
Example: static final float PI=3.14159;
3.2 Data type
Every variable in Java has a data type. Data types specify the size and type of values that can be stored.
Data types in Java divided primarily in two tyeps:
Primitive(intrinsic) and Non-primitive.
Primitive types contains Integer, Floating points, Characters, Booleans And Non-primitive types contains Classes, Interface and Arrays.
Integer:This group includes byte, short, int and long, which are whole signed numbers.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Floating-point Numbers: This group includes float and double, which represent number with fraction precision.
Characters: This group includes char, which represents character set like letters and number
Boolean: This group includes Boolean, which is special type of representation of true or false value.
Some data types with their range and size:
byte: -128 to 127 (1 byte)
short: -32,768 to +32,767 (2 bytes)
int: -2,147,483,648 to +2,147,483,647 (4 bytes)
float: 3.4e-038 to 1.7e+0.38 (4 bytes)
double: 3.4e-038 to 1.7e+308 (8 bytes)
char : holds only a single character(2 bytes)
boolean : can take only true or false (1 bytes)
3.3 Variable scope
There are three kinds of variables in Java:
Local Variable:
1. A variable that is declared inside the method is called local variable.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
2. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
3. Access modifiers cannot be used for local variables.
4. Local variables are visible only within the declared method, constructor or block.
5. There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
Instance Variable
1. A variable that is declared inside the class but outside the method is called instance variable . It is not declared as static.
2. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
3. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
4. Instance variables can be declared in class level before or after use.
5. Access modifiers can be given for instance variables.
6. Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
7. Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) should be called using the fully qualified name . ObjectReference.VariableName.
Class/static variables:
1. A variable that is declared as static is called static variable. It cannot be local.
2. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
3. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
4. Static variables are stored in static memory.
5. Static variables are created when the program starts and destroyed when the program stops.
6. Visibility is similar to instance variables.
7. Static variables can be accessed by calling with the class name ClassName.VariableName.
Example
class A{
int data=50;
//instance variable
static int m=100;
//static variable
void method(){
int n=90;
//local variable
}
}//end of class A
3.4 Typecasting
Casting is an operation that converts a value of one data type into a value of another data type.
The syntax for type casting is to give the target type in parenthesis followed by the variable name.
Example:
float f = (float) 10.1;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Int i = (int)f;
in this case, value of i is 10, the fractional part is discarded, while using type casting there is a chance of lost information that might lead to inaccurate result.
Example:
int i = 10000;
byte s = (short) i;
In this example value of s becomes 10, which is totally distorted, to ensure correctness; you can test if the value is in the correct target type range before using type casting.
Casts that results in no loss of information
byte => short, char, int, long, float, double
short => int, long, float, double
char => int, long, float, double
int => long, float, double
long => float, double
float => double
4.1 Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
- Arithmetic Operators
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
- Relational Operators
- Bitwise Operators
- Logical Operators
- Assignment Operators
- Misc Operators
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
arithmetic operators:
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Relational Operators:
There are following relational operators supported by Java language
> Greater than
< Less than
== Equal to
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
Bitwise Operators:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation.
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift & Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
Logical Operators:
The following table lists the logical operators:
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for if-then-else statement)
Assignment Operators:
There are following assignment operators supported by Java language:
= Simple assignment operator
+= Add AND assignment operator
-= Subtract AND assignment operator
*= Multiply AND assignment operator
/= Divide AND assignment operator
%= Modulus AND assignment operator
<<= Left shift AND assignment operator.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator.
^= bitwise exclusive OR and assignment operator.
|= bitwise inclusive OR and assignment operator.
Increment and Decrement Operators
Increment and decrement operators are used to add or subtract 1 from the current value of oprand.
++ increment
-- decrement
Increment and Decrement operators can be prefix or postfix.
In the prefix style the value of oprand is changed before the result of expression and in the postfix style the variable is modified after result.
For eg.
a = 9;
b = a++ + 5;
/* a=10 b=14 */
a = 9;
b = ++a + 5;
/* a=10 b=15 */
Miscellaneous Operators
There are few other operators supported by Java Language.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator.
The operator is written as:
variable x = (expression) ? value if true : value if false
Instance of Operator:
This operator is used only for object reference variables.
instanceof operator is wriiten as:
( Object reference variable ) instanceof (class/interface type)
4.2 Expression
Expressions perform operations on data and move data around. Some expressions will be evaluated for their results, some for their side effects, some for both.
An assignment expression has the following form.
variable-expression assignment-operator expression
The variable expression can be just the name of a variable, or it can be an expression that selects a variable using array indices. The value type of the right-hand-side expression must be compatible with the variable type.
An assignment expression is most often used for its side effect: it changes the value of the variable selected by the variable expression to the value of the expression on the right-hand side. The value of the assignment expression is the value that is assigned to the selected variable.
An expression can have three kinds of result:
1. a value, such as the result of: (4 * i)
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
2. a variable, such as the result of: i = 4
3. nothing (in the case of an invocation of a method declared as void)
In most common assignment expressions, the assignment operator is =. Then the assignment expression has the following form.
variable-expression = expression
The Java arithmetic and bitwise operators can be combined with = to form assignment operators.
For example, the += assignment operator indicates that the right-hand side should be added to the variable, and the *= assignment operator indicates that the right-hand side should be multiplied into the variable.
4.3 Operator precedence
Certain operators have higher priorities than others. Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. for example, the dot operator has higher precedence than the any other operator.
Precedence 15
() Parentheses
[] Array subscript
· Member selection
Precedence 14
++ Unary post-increment
-- Unary post-decrement
Precedence 13
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
+ Unary plus
- Unary minus
++ Unary pre-increment
-- Unary pre-decrement
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast
Precedence 12
* Multiplication
/ Division
% Modulus
Precedence 11
+ Addition
- Subtraction
Precedence 10
<< Bitwise left shift
>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension
Precedence 9
< Relational less than
> Relational greater than
<= Relational less than or equal
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
>= Relational greater than or equal
instanceof Type comparison (objects only)
Precedence 8
== Relational is equal to
!= Relational is not equal to
Precedence 7
& Bitwise AND
Precedence 6
^ Bitwise exclusive OR
Precedence 5
| Bitwise inclusive OR
Precedence 4
&& Logical AND
Precedence 3
|| Logical OR
Precedence 2
? : Ternary conditional
Precedence 1
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
= Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
5.1 If statement
if statement
An if statement contains a Boolean expression and block of statements enclosed within braces.
if(conditional expression)
//statement or compound statement;
else
//optional
//statement or compound statement;
//optional
If the Boolean expression is true then statement block is executed otherwise (if false) program directly goes to next statement without executing Statement block.
if....else
If statement block with else statement is known as as if...else statement. Else portion is non-compulsory.
if ( condition_one )
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
{
//statements
}
else if ( condition_two )
{
//statements
}
else
{
//statements
}
If the condition is true, then compiler will execute the if block of statements, if false then else block of statements will be executed.
nested if...else
when a series of decisions are involved, we may have to use more than one if...else statement in nested form as follows:
if(test condition1)
{
if(test condition2)
{
//statement1;
}
else
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
{
//statement2;
}
}
else
{
//statement3;
}
//statement x;
5.2 Switch statement
A switch statement is used instead of nested if...else statements. It is multiple branch decision statement.
A switch statement tests a variable with list of values for equivalence. Each value is called a case. The case value must be a constant i.
SYNTAX
switch(expression){
case constant:
//sequence of optional statements
break; //optional
case constant:
//sequence of optional statements
break; //optional
.
.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
.
default : //optional
//sequence of optional statements
}
Individual case keyword and a semi-colon (:) is used for each constant.
Switch tool is used for skipping to particular case, after jumping to that case it will execute all statements from cases beneath that case this is called as ''Fall Through''.
In the example below, for example, if the value 2 is entered, then the program will print two one something else!
switch(i)
{
case 4: System.out.println(''four'');
break;
case 3: System.out.println(''three'');
break;
case 2: System.out.println(''two'');
case 1: System.out.println(''one'');
default: System.out.println(''something else!'');
}
To avoid fall through, the break statements are necessary to exit the switch.
If value 4 is entered, then in case 4 it will just print four and ends the switch.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
The default label is non-compulsory, It is used for cases that are not present.
5.3 While loop
Java while loop is used to execute statement(s) until a condition holds true.
SYNTAX
while (condition(s)) {
// statements
}
If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false.
1. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false.
2. You can test multiple conditions such as
while ( a > b && c != 0) {
// statements
}
Loop body is executed till value of a is greater than value of b and c is not equal to zero.
3. Body of loop can contain more than one statement.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}.
It is recommended to use braces always to make your program easily readable and understandable.
5.4 Do While loop
The while loop makes a test condition before the loop is executed.Therefore, the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt.
On some occasions it might be necessary to execute the body of the loop before the test is performed.
Such situations can be handled with the help of the do statement.
SYNTAX
do {
//statement(s)...
} while (condition);
On reaching the do statement, program evaluate the body of loop first.
At the end of the loop, the condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of loop again and again till condition becomes false.
int i =0;
do
{
System.out.println("i is : " + i);
i++;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}while(i < 5);
Output would be
i is : 0
i is : 1
i is : 2
i is : 3
i is : 4
5.5 For loop
Java for loop used to repeat execution of statement(s) until a certain condition holds true.
The general form of the for statement can be expressed as follows:
for (initialization; termination; increment)
{
statement(s)...
}
You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement.
All three components of for loop are optional.
For example, to execute a statement 5 times:
for (i = 0; i < 5; i++)
statements...;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Another way of doing this is: i = 4;
while (i>=0)
statements...;
6.5 Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.
Rules for method overriding:
1. The argument list should be exactly the same as that of the overridden method.
2. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.
3. The access level cannot be more restrictive than the overridden method's access level.
4. Instance methods can be overridden only if they are inherited by the subclass.
5. A method declared final cannot be overridden.
6. A method declared static cannot be overridden but can be re-declared.
7. If a method cannot be inherited, then it cannot be overridden.
8. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
9. A subclass in a different package can only override the non-final methods declared public or protected.
10. Constructors cannot be overridden.
Advantage:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class(base class).
Example:
class Base{
public void display()
{
System.out.println("this is base class");
}
}
class Child extends Base{
public void display(){
System.out.println("this is child class");
}
public static void main( String args[]) {
Child obj = new Child();
obj.display();
}
}
output
this is child class
Using the super keyword:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
When invoking a base class version of an overridden method the super keyword is used. class Base{
public void display()
{
System.out.println("this is base class");
}
}
class Child extends Base{
public void display(){
super.display(); // invokes the super class method System.out.println("this is child class");
}
public static void main( String args[]) {
Child obj = new Child();
obj.display();
}
}
output
this is base class
this is child class
6.6 Static keyword
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 class than instance of the class.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
Variables and methods marked static belong to the class rather than to any particular instance of the class. These can be used without having any instances of that class at all. Only the class is sufficient to invoke a static method or access a static variable. A static variable is shared by all the instances of that class i.e only one copy of the static variable is maintained.
class Counter
{
static int animalCount=0;
public Counter()
{
count+=1;
}
public static void main(String[] args)
{
new Counter();
new Counter();
new Counter();
System.out.println(''The Number of Animals is: ''+count);
}
}
Output:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
The Number of Animals is: 3.
A static method cannot access non-static/instance variables, because a static method is never associated with any instance. The same applies with the non-static methods as well, a static method can't directly invoke a non-static method. But static method can access non-static methods by means of declaring instances and using them.
Accessing static variables and methods
In case of instance methods and instance variables, instances of that class are used to access them.
<objectReference>.<instanceVariable>
<objectReference>.<instanceMethod>
class Counter
{
static int count=0;
public Counter()
{
count+=1;
}
public static int getCount()
{
return count;
}
}
class TestAnimal
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
{
public static void main(String[] args)
{
new Counter();
new Counter();
new Counter();
System.out.println(''The Counter is: ''+ Counter.getCount());
/* Notice the way in which the Static method is called using the class name followed by static method. */
}
}
Remember that static methods can't be overridden. They can be redefined in a subclass, but redifining and overriding aren't the same thing. Its called as Hiding.
6.7 Inheritance
Inheritance is one of the key features of Object Oriented Programming.
Inheritance provided mechanism that allowed a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
Inheritance defines is-a relationship between a Super class and its Sub class. extends and implements keywords are used to describe inheritance in Java.
Why use inheritance in java
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
-For Method Overriding (so runtime polymorphism can be achieved).
-For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
extends is the keyword used to inherit the properties of a class.
super keyword
In Java, super keyword is used to refer to immediate parent class of a class. In other words super keyword is used by a subclass whenever it need to refer to its immediate super class.
6.8 Types of Inheritance
Syntax of Java Inheritance
Single inheritance is damn easy to understand. When a class extends another one class only then we call it a single inheritance. The below example shows that class B extends only one class which is A. Here A is a parent class of B and B would be a child class of A.
class A{
}
class B extends A{
}
2) Multiple Inheritance
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
''Multiple Inheritance'' refers to the concept of one class extending (Or inherits) more than one base class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with ''multiple inheritance'' is that the derived class will have to manage the dependency on two base classes.
Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.
class A{
}
class B{
}
class C extends A,B{
}
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class. As you can see in below example C is subclass or child class of B and B is a child class of A.
class A{
}
class B extends A{
}
class C extends B{
}
4) Hierarchical Inheritance
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.
class A{
}
class B extends A{
}
class C extends A{
}
class D extends A{
}
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple inheritance.
A hybrid inheritance can be achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes you heard it right. By using interfaces you can have multiple as well as hybrid inheritance in Java.
6.9 Final keyword
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
- variable
- method
- class
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.
class Game{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Game obj=new Game();
obj.run();
}
}//end of class
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Example of final method
class Game{
final void run(){System.out.println("bowling");}
}
class Cricket extends Game{
void run(){System.out.println("bowling safely with 100kmph");}
public static void main(String args[]){
Cricket cricket= new Cricket();
cricket.run();
}
}
Output:Compile Time Error
3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
final class Game{}
class Cricket extends Game{
void run(){System.out.println("bowling safely with 100kmph");}
public static void main(String args[]){
Cricket cricket= new Cricket();
cricket.run();
}
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Output:Compile Time Error
6.10 Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
There are two ways to achieve abstraction in java
- Abstract class (0 to 100%)
- Interface (100%)
Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
Example abstract class
abstract class A{
}
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Example abstract method
abstract void printStatus();
//no body and abstract
7.1 Arrays
Array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Types of Array in java
1. Single Dimensional Array
2. Multidimensional Array
1. Single Dimensional Array
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
dataType[] arrayName;
or
dataType arrayName[];
Instantiating Arrays:
You can instantiate an array by using the new operator with the following syntax:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
arrayName = new dataType[arraySize];
The above statement does two things:
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayName.
2. Multidimensional Array
Syntax to Declare Multidimensional Array in java
dataType[][] arrayName; or
dataType arrayName[][];
Example to instantiate Multidimensional Array
int[][] arr=new int[2][3];
//2 row and 3 column
Example to initialize Multidimensional Array in java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
Passing Arrays to Methods:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:
public static void display(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
Returning an Array from a Method:
A method may also return an array. For example, the method shown below returns an array that is the copy of another array:
public static int[] copyarray(int[] list) {
int[] result = new int[list.length];
for (int i = 0; i < list.length - 1 ; i++) {
result[i] = list[i];
}
return result;
}
Arrays Methods :
Arrays.binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key.
Arrays.equals(long[] a, long[] a2)
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.
Arrays.fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other primitive data types (Byte, short, Int etc.)
Arrays.sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other primitive data types ( Byte, short, Int, etc.)
7.2 String
In java, string is basically an object that represents sequence of char values. The Java platform provides the String class to create and manipulate strings.
Creating Strings:
1) The most direct way to create a string is to write:
String str1 = "Hello Java!";
2) Using another String object
String str2 = new String(str1);
3) Using new Keyword
String str3 = new String("Java");
4) Using + operator (Concatenation)
String str4 = str1 + str2;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
or,
String str5 = "hello"+"Java";
String Length:
length() method returns the number of characters contained in the string object.
String str1 = "Hello Java";
int len = str1.length();
System.out.println( "String Length is : " + len );
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:
"Hello ".concat("Java");
Strings are more commonly concatenated with the + operator, as in:
"Hello " + " Java" + "!"
which results in:
"Hello Java!"
String Methods :
1 char charAt(int index)
returns char value for the particular index
2 int length()
returns string length
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
3 static String format(String format, Object... args)
returns formatted string
4 static String format(Locale l, String format, Object... args)
returns formatted string with given locale
5 String substring(int beginIndex)
returns substring for given begin index
6 String substring(int beginIndex, int endIndex)
returns substring for given begin index and end index
7 boolean contains(CharSequence s)
returns true or false after matching the sequence of char value
8 static String join(CharSequence delimiter, CharSequence... elements)
returns a joined string
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
returns a joined string
10 boolean equals(Object another)
checks the equality of string with object
11 boolean isEmpty()
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
checks if string is empty
12 String concat(String str)
concatinates specified string
13 String replace(char old, char new)
replaces all occurrences of specified char value
14 String replace(CharSequence old, CharSequence new)
replaces all occurrences of specified CharSequence
15 String trim()
returns trimmed string omitting leading and trailing spaces
16 String split(String regex)
returns splitted string matching regex
17 String split(String regex, int limit)
returns splitted string matching regex and limit
18 String intern()
returns interned string
19 int indexOf(int ch)
returns specified char value index
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
20 int indexOf(int ch, int fromIndex)
returns specified char value index starting with given index
21 int indexOf(String substring)
returns specified substring index
22 int indexOf(String substring, int fromIndex)
returns specified substring index starting with given index
23 String toLowerCase()
returns string in lowercase.
24 String toLowerCase(Locale l)
returns string in lowercase using specified locale.
25 String toUpperCase()
returns string in uppercase.
26 String toUpperCase(Locale l)
returns string in uppercase using specified locale.
7.3 Vectors
Vector implements List Interface. Like ArrayList it also maintains insertion order but it is rarely used in non-thread environment as it is synchronized and due to which it gives poor performance in searching, adding, delete and update of its elements.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Three ways to create vector class object:
Method 1:
Vector vec = new Vector();
It creates an empty Vector with the default initial capacity of 10. It means the Vector will be re-sized when the 11th elements needs to be inserted into the Vector. Note: By default vector doubles its size.
i.e. In this case the Vector size would remain 10 till 10 insertions and once we try to insert the 11th element It would become 20 (double of default capacity 10).
Method 2:
Vector object= new Vector(int initialCapacity)
Vector vec = new Vector(3);
It will create a Vector of initial capacity of 3.
Method 3:
Vector object= new vector(int initialcapacity, capacityIncrement)
Vector vec= new Vector(4, 6)
Here we have provided two arguments. The initial capacity is 4 and capacityIncrement is 6. It means upon insertion of 5th element the size would be 10 (4+6) and on 11th insertion it would be 16(10+6).
Vector Methods:
void addElement(Object element):
It inserts the element at the end of the Vector.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
int capacity():
This method returns the current capacity of the vector.
int size():
It returns the current size of the vector.
void setSize(int size):
It changes the existing size with the specified size.
boolean contains(Object element):
This method checks whether the specified element is present in the Vector. If the element is been found it returns true else false.
boolean containsAll(Collection c):
It returns true if all the elements of collection c are present in the Vector.
Object elementAt(int index):
It returns the element present at the specified location in Vector.
Object firstElement():
It is used for getting the first element of the vector.
Object lastElement():
Returns the last element of the array.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Object get(int index):
Returns the element at the specified index.
boolean isEmpty():
This method returns true if Vector doesn't have any element.
boolean removeElement(Object element):
Removes the specifed element from vector.
boolean removeAll(Collection c):
It Removes all those elements from vector which are present in the Collection c.
void setElementAt(Object element, int index):
It updates the element of specifed index with the given element.
7.4 Wrapper Class
As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance.
Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object and give back the data type.
It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
The list of eight wrapper classes are given below:
Primitive Type => Wrapper class
boolean => Boolean
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
char => Character
byte => Byte
short => Short
int => Integer
long => Long
float => Float
double => Double
Creating objects of the Wrapper classes
All the wrapper classes have constructors which can be used to create the corresponding Wrapper class
For example
Integer intObject = new Integer (15);
Retrieving the value wrapped by a wrapper class object
Each of the eight wrapper classes have a method to retrieve the value that was wrapped in the object.
For example, to retrieve the value stored in the Integer object intObject, we use the following statement.
int x = intObject.intValue();
Similarly, we have methods for the other seven wrapper classes: byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanValue().
Auto boxing and auto unboxing
Above given method can become quite cumbersome.
As an alternative, there exists auto boxing and autounboxing.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Auto boxing refers to an implicit call to the constructor and auto unboxing refers to an implicit call to the *value() method.
Therefore, a new wrapper object can be created by specifying the value to be wrapped just as we would do for a primitive data type variable. Also, the value can be retrieved and used in a simple way by specifying the object name.
Look at the following code:
Integer intObject = 34;
int x=intObject;
int x = intObject + 7;
The above statements are equivalent to the following set of statements
Integer intObject = new Integer (34);
int x = intObject.intValue();
int x = intObject .intValue()+ 7;
Similarly, auto boxing and auto boxing apply to other wrapper classes also.
8.1 Defining Interfaces
An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods.
A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviours of an object. And an interface contains behaviours that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
The General form of an interface definition is:
[visibility] interface InterfaceName [extends other interfaces]
{
variables declarations;
abstract method declarations;
}
here, interface is the keyword and InterfaceName is any valid java variable(just like class name).
variables are declared as follows:
static final tyoe VariableName=Value;
example:
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Output: Hello
8.2 Extending Interfaces
An interface can extend another interface, similarly to the way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
this is achieved using the keyword extends as shown below:
public class C extends A implements B {
//trying to override doSomthing...
public int myMethod(int x) {
return doSomthingElse(x);
}
}
Example
interface ItemConstants
{
int code=2015;
string name="Akshay";
}
interface Item extends ItemConstants
{
void display();
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
8.3 Implementing Interfaces
A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.
class classname implements interfacename
{
body of classname
}
here the classname "implements" the interface interfacename. A more general form of implementation may look like this:
class classname extends superclass implements interface1,interface2,...
{
body of classname
}
Example:
interface MyInterface
{
public void method1();
public void method2();
}
class XYZ implements MyInterface
{
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new XYZ();
obj. method1();
}
}
Output:
implementation of method1
8.4 Accessing Interface
interfaces can be used to declare a set of constants that can be used in different classes.
This is similar to creating header files in c++ to contain large number of constants.
Since such interfaces do not contain methods,there is no need to worry about implementing any methods.
The constant value will be available to any class that implements the interface.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
The values can be used in any method, as part of any variable declaration, or anywhere where we can use a final value.
Example:
interface A
{
int m=10;
int n=50;
}
class B implements A
{
int x=m;
void methodB(int size)
{
...
...
if(size<n)
}
}
9.1 Introduction to packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Example
The package keyword is used to create a package in java.
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
9.2 Java API package
An Application Programming Interface (API), in the context of Java, is a collection of prewritten packages, classes, and interfaces with their respective methods, fields and constructors.
Similar to a user interface, which facilitates interaction between humans and computers, an API serves as a software program interface facilitating interaction.
In Java, most basic programming tasks are performed by the API's classes and packages, which are helpful in minimizing the number of lines written within pieces of code.
Java system packages and their classes:
java.lang
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
language support classes.They include classes for primitive types, strings,math functions,threads and exceptions.
java.util
Language utility classes such as vectors, hash tables, random numbers, date etc.
java.io
Input/Output support classes. They provides facilities for the input and output of data.
java.awt
Set of classes for implementing graphical user interface.They include classes for windows, buttons, lists, menus and so on.
java.net
classes for networking. They include classes for communicating with local computers as well as with internet servers.
java.applet
Classes for creating and implement?ing applets.
9.3 System packages
The package named java contains the package awt,which in turn contains various classes required for implementing graphical user interface.
There are two ways of accessing the classes stored in a package.
The first approach is to use the fully qualified class name of the class that we want to use.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
for example, if we want to refer to the class Color in the awt package, then we may do so as follows
java.awt.Colour
Notice that awt is a package within the package java and the hierarchy is represented by separating the levels with dots.
This approach is perhaps the best and easiest one if we need to access the class only once or when we need not have to access any other classes of the package.
But, in many situations, we might want to use a class in a number of places in the program or we may like to use many of the classes contained in a package.
We may achieve this easily as follows:
import packagename.classname;
or
import packagename.*
These are known as import statements and must appear at the top of the file, before any class declarations, import is a keyword.
10.1 Creating thread
Threads are implemented in the form of objects that contain a method called run().
The run() method is the heart and soul of any thread.
public void run()
{
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
/* Your implementation of thethread here*/
}
The run() method should be invoked by an object of the concerned thread.This can be achieved by creating the thread and initiating it with the help of another thread method called start().
A new thread can be created in two ways:
1. By creating a thread class:
Define a class that extends Thread class and override its run() method with the code required by the thread.
2. By converting a class to a thread:
Define a class that implements Runnable interface.The runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread.
10.2 Stopping & blocking
Stopping a thread:
Whenever we want to stop a thread from running further,we may do so by calling its stop() method, like:
aThread.stop();
This statement cause the thread to move to the dead state.The stop method may used when the premature death of a thread is desired.
Blocking a thread:
A thread can also be temporarily suspended or blocked from entering into the runnable and subsequently running state by using either of the following thread methods:
sleep()
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
//blocked for a specified time
suspend()
//blocked until further orders
wait()
//blocked until certain condition occurs
These methods cause the thread to go into the blocked(or not-runnable) state.
10.3 Life Cycle
The life cycle of the thread in java is controlled by JVM.
A thread can be in one of the five states.
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently waiting for other thread to finish using thread join or it can be waiting for some resources to available
5) Terminated
A thread is in terminated or dead state when its run() method exits.
10.4 Exception & priority
Exception
IllegalArgumentException
if the priority is not in the range MIN_PRIORITY to MAX_PRIORITY.
SecurityException
if the current thread cannot modify this thread.
Priority of a Thread (Thread Priority):
Java permits us to set the priority of a thread using the setPriority() method as follows:
ThreadName.setPriority(intNumber);
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
3 constants defiend in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1.
The value of MAX_PRIORITY is 10.
Example:
class TestPriority extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestPriority1 m1=new TestPriority1();
TestPriority1 m2=new TestPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
10.5 Synchronization
Thread synchronization is the concurrent execution of two or more threads that share critical resources.
Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable at the same time.
if multiple threads try to write within a same file then they may corrupt the data because one of the threads can overrite data or while one thread is opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors.
Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block.
Syntax
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
synchronized (object reference expression)
{
//code block
}
Here, the object identifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents.
10.6 Runnable Interface
A Thread can be created by extending Thread class also. But Java allows only one class to extend, it wont allow multiple inheritance. So it is always better to create a thread by implementing Runnable interface. Java allows you to impliment multiple interfaces at a time.
By implementing Runnable interface, you need to provide implementation for run() method.
To run this implementation class, create a Thread object, pass Runnable implementation class object to its constructor. Call start() method on thread class to start executing run() method.
Implementing Runnable interface does not create a Thread object, it only defines an entry point for threads in your object. It allows you to pass the object to the Thread(Runnable implementation) constructor.
To create a thread using Runnable, a class must implement Java Runnable interface.
For example of Thread using runnable, reffer "Thread Example" program from programs section of this app
11.1 Exceptions
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
An Exception can be anything which interrupts the normal execution of the program. When an exception occurs program processing terminates abnormally. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled.
An exception can occur for many different reasons like Opening a non-existing file, Network connection problem, invalid data entered, class file missing which was supposed to be loaded and so on.
Types of exceptions
Checked exceptions
A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions.
If these exceptions are not handled/declared in the program, it will give compilation error.
Examples of Checked Exceptions :-
ClassNotFoundException
IllegalAccessException
NoSuchFieldException
EOFException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer has handled them or not but it's the duty of the programmer to handle these exceptions and provide a safe exit.
These exceptions need not be included in any method's throws list because compiler does not check to see if a method handles or throws these exceptions.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Examples of Unchecked Exceptions:-
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.
Advantages of Exception Handling
1. Exception handling allows us to control the normal flow of the program by using exception handling in program.
2. It throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.
3. It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks.
11.2 Try Catch
A method catches an exception using a combination of the try and catch keywords.
A try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
The code which is prone to exceptions is placed in the try block, when an exception occurs, that exception occurred is handled by catch block associated with it.
Every try block should be immediately followed either by a class block or finally block.
Multiple catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
this is just an example of 3 catch statements you can have any number of them If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
Finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
Syntax
try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}
11.3 Custom Exception
Custom exceptions in java are also known as User defined exceptions.
Most of the times when we are developing java program, we often feel a need to use our own exceptions. These exceptions are known as Custom exceptions or User defined.
We can create our own exception sub class simply by extending java Exception class.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
We can define a constructor for our Exception sub class (not compulsory) and can override the toString() function to display our customized message on catch.
class MyException extends Exception{
String str;
MyException(String str) {
this.str=str;
}
public String toString(){
return ("message = "+str);
}
}
class CustomException{
public static void main(String args[]){
try{
throw new MyException("HELLO");
}
catch(MyException e){
System.out.println(e);
}
}
}
Output:
message= HELLO
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Note:
1. User defined exception needs to inherit (extends) Exception class in order to act as an exception.
2. throw keyword is used to throw such exceptions.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.
12.1 Introduction
An applet is a small Java program that is embedded and ran in some other Java interpreter program such as a Java technology-enabled browser Or Sun's applet viewer program called appletviewer.
An applet can be a fully functional Java application because it has the entire Java API at its disposal.
Key Points
An applet program is a written as a inheritance of the java.Appletclass
There is no main() method in an Applet.
Applets are designed to be embedded within an HTML page.
An applet uses AWT for graphics
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
Advantages
1. Automatically integrated with HTML; hence, resolved virtually all installation issues.
2. Can be accessed from various platforms and various java-enabled web browsers.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
3. Can provide dynamic, graphics capabilities and visualizations
4. Implemented in Java, an easy-to-learn OO programming language
5. Alternative to HTML GUI design
6. Safe! Because of the security built into the core Java language and the applet structure, you don't have to worry about bad code causing damage to someone's system
7. Can be launched as a standalone web application independent of the host web server
Disadvantages
1. Applets can't run any local executable programs
2. Applets can't with any host other than the originating server
3. Applets can't read/write to local computer's file system
4. Applets can't find any information about the local computer
5. All java-created pop-up windows carry a warning message
6. Stability depends on stability of the client's web server
7. Performance directly depend on client's machine
12.2 Life Cycle
init:
This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed.
start:
This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.
stop:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.
destroy:
This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.
paint:
Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.
12.3 Creating an Executable Applet
To create an executable jar file there should be a main class (a class with a main method) inside the jar to run the software.
An applet has no main method since it is usually designed to work inside a web browser.
Executable applet is nothing but the .class file of applet, which is obtained by compiling the source code of the applet.
Compiling the applet is exactly the same as compiling an application using following command.
javac appletname.java
The compiled output file called appletname.class should be placed in the same directory as the source file.
12.4 Designing a Web Page
Java applet are programs that reside on web page. A web page is basically made up of text and HTML tags that can be interpreted by a web browser or an applet viewer.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
HTML files should be stored in the same directory as the compiled code of the applets.
A web page is marked by an opening HTML tag <HTML> and closing HTML tag </HTML> and is divided into the following three major parts:
1. Comment Section
2. Head Section
3. Body Section
Comment Section
This is very first section of any web page containing the comments about the web page functionality. A comment line begins with <! And ends with a > and the web browsers will ignore the text enclosed between them. The comments are optional and can be included anywhere in the web page.
Head Section
This section contains title, heading and sub heading of the web page. The head section is defined with a starting <Head> tag and closing </Head> tag.
<Head>
<Title>Hello World Applet</Title>
</Head>
Body Section
The entire information and behaviour of the web page is contained in it, It defines what the data placed and where on to the screen. It describes the color, location, sound etc. of the data or information that is going to be placed in the web page.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
<body>
<h1>Hi, This is My First Java Applet on the Web!</h1>
</body>
Applet Tag
The <Applet...> tag supplies the name of the applet to be loaded and tells the browser how much space the applet requires.
The <Applet> tag given below specifies the minimum requirements to place the Hellojava applet on a web page.
<Applet code = "Hellojava.class"
width = 400
Height = 200 >
</Applet>
This HTML code tells the browser to load the compiled java applet Hellojava.class, which is in the same directory as this HTML file.
It also specifies the display area for the applet output as 400 pixels width and 200 pixels height.
After you create this file, you can execute the HTML file called RunApp.html (say) on the command line.
c:\ appletviewer RunApp.html
12.5 Running an Applet
To execute an applet with an applet viewer, you may also execute the HTML file in which it is enclosed, eg.
c:\>appletviewer RunApp.html
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Execute the applet the applet viewer, specifying the name of your applet's source file.
The applet viewer will encounter the applet tage within the comment and execute your applet.
13.1 Stream Classes
The java.io package contains Stream classes which provide capabilities for processing all types of data.
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java.
In general, a stream means continuous flow of data. Streams are clean way to deal with input/output without having every part of your code understand the physical. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.
These classes may be categorized into two groups based on their data type handling capabilities:-
1. Byte Stream
2. Charater Stream
The InputStream & OutputStream class providing support for handling I/O operations on bytes are type of byte stream.
The Reader & Writer class providing support for handling I/O operations on characters are type of char stream. Character stream uses Unicode and therefore can be internationalized.
13.2 Byte Stream
ByteStream classes are to provide an surrounding to handle byte-oriented data or I/O.
ByteStream classes are having 2 abstract class InputStream & OutputStream.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.
InputStream
- It is an abstract class in which defines an interface known as Closable interface.
- Methods in this class will throw an IOException.
OutputStream
- It is an abstract class in which defines an interface known as Closable & Flushable interface.
- Methods in this class returns void and throws IOException.
methods by InputStream abstract class
int read()
it returns integer of next available input of bye
int read(byte buffer[ ])
it read up to the length of byte in buffer
int read(byte buffer[ ], int offset, int numBytes)
it read up to the length of byte in buffer starting form offset
int available()
It gets the no.of bytes of input available.
void reset()
it reads the input pointer.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
long skip(long numBytes)
it returns the bytes ignored.
void close()
close the source of input.
methods by OutputStream abstract class
void write(int b)
it writes a single byte in output.
void write(byte buffer[ ])
it write a full array of bytes to an output stream
void write(byte buffer[ ], int offset, int numBytes)
it writes a range of numBytes from array buffer starting at buffer offset.
void close()
close the source of output
void flush()
it marks a point to input stream that will stay valid until numBytes are read.
13.2 Byte Stream
ByteStream classes are to provide an surrounding to handle byte-oriented data or I/O.
ByteStream classes are having 2 abstract class InputStream & OutputStream.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.
InputStream
- It is an abstract class in which defines an interface known as Closable interface.
- Methods in this class will throw an IOException.
OutputStream
- It is an abstract class in which defines an interface known as Closable & Flushable interface.
- Methods in this class returns void and throws IOException.
methods by InputStream abstract class
int read()
it returns integer of next available input of bye
int read(byte buffer[ ])
it read up to the length of byte in buffer
int read(byte buffer[ ], int offset, int numBytes)
it read up to the length of byte in buffer starting form offset
int available()
It gets the no.of bytes of input available.
void reset()
it reads the input pointer.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
long skip(long numBytes)
it returns the bytes ignored.
void close()
close the source of input.
methods by OutputStream abstract class
void write(int b)
it writes a single byte in output.
void write(byte buffer[ ])
it write a full array of bytes to an output stream
void write(byte buffer[ ], int offset, int numBytes)
it writes a range of numBytes from array buffer starting at buffer offset.
void close()
close the source of output
void flush()
it marks a point to input stream that will stay valid until numBytes are read.
13.3 Character Stream
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are , Reader and Writer.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
Reader
- It is an abstract class used to input character.
- It implements 2 interfaces Closable & Readable.
- Methods in this class throws IO Exception(Except markSupported()).
Writer
- Writer is an abstract class used to output character.
- It implements 3 interfaces Closable, Flushable & Appendable.
methods of Reader abstract class
abstract void close()
close the source of input.
void mark(int numChars)
it marks a point to input stream that will stay valid until numChars are read.
boolean markSupported()
it returns true if mark() support by stream.
int read()
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
it returns integer of next available character from input
int read(char buffer[])
it read up to the length of byte in buffer
abstract read(byte buffer[], int offset, int numBytes)
it read up to the length of character in buffer starting form offset
void reset()
it reads the input pointer.
long skip(long numBytes)
it returns the character ignored.
boolean ready()
if input request will not wait returns true, otherwise false
methods of Writer abstract class
write append(char ch)
It append the 'ch' character at last of output stream
write append(charSequence chars)
append the chars at end of output stream.
write append(charSequence chars, int begin, int end)
append the characters specified in the range.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
abstract void close()
close the output stream
abstract void flush()
it flush the output buffer.
void write(char buffer[])
writes array of character to output stream.
abstract void write(char buffer[], int offset, int numChars)
it writes a range of characters from buffer starting form offset
void write(String str)
it writes the str to output stream
void write(String str, int offset, int numChars)
it writes a range of character from the string str starting at offset.
13.4 Standard Streams
Java provides following three standard streams
Standard Input:
This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Standard Output:
This is used to output the data produced by the user's program and usually a computer screen is used to standard output stream and represented as System.out.
Standard Error:
This is used to output the error data produced by the user's program and usually a computer screen is used to standard error stream and represented as System.err.
13.5 File
- File class is used to support with Files and File systems.
- File class describes properties of itself.
- File class has its objects which is used to handle or get data stored in disk.
- File class has some constructors which is used to describe the file path.
Constructors :
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URl uriObj)
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file.:
InputStream f = new FileInputStream("C:/java/hello");
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
I/O Exceptions
EOFException
It indicates the signal are reached to end of file during input.
FileNotFoundException
It indicates that the file not found at specified path.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
InterruptedIOException
It indicates that an I/O Exception has occurred
I/O Exception
It indicates I/O Exception some sort has occurred.
13.6 Directory
A directory is a File which can contains a list of other files and directories.
You use File object to create directories, to list down files available in a directory.
For complete detail check a list of all the methods which you can call on File object and what are related to directories.
Creating Directories:
There are two useful File utility methods, which can be used to create directories:
The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the directory.
Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories available in a directory
Deleting Directories:
To delete a directory, you can simply use the File.delete(), but the directory must be empty in order to delete it.
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Often times, you may require to perform recursive delete in a directory, which means all it's sub-directories and files should be delete as well.
String Compare:
Program:
public class StringCompare{
public static void main(String args[]){
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;
/* compare two strings, case sensitive */
System.out.println( str.compareTo(anotherString) );
/* compare two strings, ignores character case */
System.out.println( str.compareToIgnoreCase(anotherString) );
/* compare string with object */
System.out.println( str.compareTo(objStr) );
}
}
Output:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
-32
0
0
Garbage Collection:
Program:
import java.util.*;
class GarbageCollection
{
public static void main(String s[]) throws Exception
{
Runtime rs = Runtime.getRuntime();
System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory());
rs.gc();
System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory());
}
}
Output:
Free memory in JVM before Garbage Collection
Free memory in JVM after Garbage Collection
Create File:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Program:
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try{
File file = new File("C:/myfile.txt");
if(file.createNewFile())
System.out.println("Success!");
else
System.out.println
("Error, file already exists.");
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
Output:
Success!
Last Modification Time:
Program:
import java.io.*;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
import java.util.Date;
public class GetLastMod {
public static void main(String[] args) {
File file = new File("C://FileIO//demo.txt");
long lastModified = file.lastModified();
System.out.println("File was last modifed at : " + new Date(lastModified));
}
}
Output:
File was last modifed at : Fri Nov 13 16:37:57 MST 2015
Random Numbers:
Program:
import java.util.*;
class RandomNumbers {
public static void main(String[] args) {
int c;
Random t = new Random();
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
// random integers in [0, 100]
for (c = 1; c <= 10; c++) {
System.out.println(t.nextInt(100));
}
}
}
Output:
62
47
60
17
52
59
24
47
2
21
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
HelloWorld:
Program:
classHelloWorld
{
publicstaticvoidmain(Stringargs[])
{
System.out.println("HelloWorld");
}
}
Output:
HelloWorld
Addition:
Program:
importjava.util.Scanner;
classAddNumbers
{
publicstaticvoidmain(Stringargs[])
{
intx,y,z;
System.out.println("Entertwointegerstocalculatetheirsum ");
Scannerin=newScanner(System.in);
x=in.nextInt();
y=in.nextInt();
z=x+y;
System.out.println("Sum ofenteredintegers="+z);
}
}
Output:
Entertwointegerstocalculatetheirsum
4
5
Sum ofenteredintegers=9
IfElseExample:
Program:
importjava.util.Scanner;
classIfElse{
publicstaticvoidmain(String[]args){
intmarksObtained,passingMarks;
passingMarks=40;
Scannerinput=newScanner(System.in);
System.out.println("Inputmarksscoredbyyou");
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
marksObtained=input.nextInt();
if(marksObtained>=passingMarks){
System.out.println("Youpassedtheexam.");
}
else{
System.out.println("Unfortunatelyyoufailedtopasstheexam.");
}
}
}
Output:
Inputmarksscoredbyyou
71
Youpassedtheexam.
Inputmarksscoredbyyou
37
Unfortunatelyyoufailedtopasstheexam.
WhileLoopExample:
Program:
importjava.util.Scanner;
classWhileLoop{
publicstaticvoidmain(String[]args){
intn;
Scannerinput=newScanner(System.in);
System.out.println("Inputaninteger");
while((n=input.nextInt())!=0){
System.out.println("Youentered"+n);
System.out.println("Inputaninteger");
}
System.out.println("Outofloop");
}
}
Output:
Inputaninteger
7
Youentered7
Inputaninteger
-2
Youentered-2
Inputaninteger
9546
Youentered9546
Inputaninteger0
Outofloop
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
DoWhileExample:
Program:
publicclassDoWhileExample{
publicstaticvoidmain(String[]args){
/*
Dowhileloopexecutesstatmentuntilcertainconditionbecomefalse.
*/
inti=0;
do
{
System.out.println("iis:"+i);
i++;
}while(i<5);
}
}
Output:
iis:0
iis:1
iis:2
iis:3
iis:4
ForLoopExample:
Program:
classForLoop{
publicstaticvoidmain(String[]args){
intc;
for(c=1;c<=10;c++){
System.out.println(c);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
SwitchCaseExample:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Program:
publicclassSwitchStatementExample{
publicstaticvoidmain(String[]args){
for(inti=0;i<=3;i++)
{
switch(i)
{
case0:
System.out.println("iis0");
break;
case1:
System.out.println("iis1");
break;
case2:
System.out.println("iis2");
break;
default:
System.out.println("iisgraterthan2");
}
}
}
}
Output:
iis0
iis1
iis2
iisgraterthan2
ContinueExample:
Program:
publicclassContinueExample{
publicstaticvoidmain(String[]args){
/*
*Continuestatementisusedtoskipaparticulariterationoftheloop
*/
intintArray[]=newint[]{1,2,3,4,5};
System.out.println("Allnumbersexceptfor3are:");
for(inti=0;i<intArray.length;i++)
{
if(intArray[i]==3)
continue;
else
System.out.println(intArray[i]);
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
}
Output:
Allnumbersexceptfor3are:
1
2
4
5
EvenorOdd:
Program:
importjava.util.Scanner;
classOddOrEven
{
publicstaticvoidmain(Stringargs[])
{
intx;
System.out.println("Enteranintegertocheckifitisoddoreven");
Scannerin=newScanner(System.in);
x=in.nextInt();
if(x%2==0)
System.out.println("Youenteredanevennumber.");
else
System.out.println("Youenteredanoddnumber.");
}
}
Output:
Enteranintegertocheckifitisoddoreven
6
Youenteredanevennumber.
Enteranintegertocheckifitisoddoreven
5
Youenteredanoddnumber.
PrimeNumber:
Program:
importjava.util.*;
classPrimeNumbers
{
publicstaticvoidmain(Stringargs[])
{
intn,status=1,num =3;
Scannerin=newScanner(System.in);
System.out.println("Enterthenumberofprimenumbersyouwant");
n=in.nextInt();
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
if(n>=1)
{
System.out.println("First"+n+"primenumbersare:-");
System.out.println(2);
}
for(intcount=2;count<=n;)
{
for(intj=2;j<=Math.sqrt(num);j++)
{
if(num%j==0)
{
status=0;
break;
}
}
if(status!=0)
{
System.out.println(num);
count++;
}
status=1;
num++;
}
}
}
Output:
Enterthenumberofprimenumbersyouwant
10
First10primenumbersare:-
2
3
5
7
11
13
17
19
23
29
FindFactorial:
Program:
importjava.util.Scanner;
classFactorial
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
{
publicstaticvoidmain(Stringargs[])
{
intn,c,fact=1;
System.out.println("Enteranintegertocalculateit'sfactorial");
Scannerin=newScanner(System.in);
n=in.nextInt();
if(n<0)
System.out.println("Numbershouldbenon-negative.");
else
{
for(c=1;c<=n;c++)
fact=fact*c;
System.out.println("Factorialof"+n+"is="+fact);
}
}
}
Output:
Enteranintegertocalculateit'sFactorial
6
Factorialof6is=720
Factorialusingrecursion:
Program:
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
publicclassFactorial{
publicstaticvoidmain(Stringargs[])throwsNumberFormatException,IOException{
System.out.println("Enteranintegertocalculateit'sfactorial");
//getinputfrom theuser
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
inta=Integer.parseInt(br.readLine());
//calltherecursivefunctiontogeneratefactorial
intresult=fact(a);
System.out.println("Factorialof"+a+"is="+result);
}
staticintfact(intb)
{
if(b<=1)
//ifthenumberis1thenreturn1
return1;
else
//elsecallthesamefunctionwiththevalue-1
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
returnb*fact(b-1);
}
}
Output:
Enteranintegertocalculateit'sFactorial
6
Factorialof6is=720
AreaofCircle:
Program:
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
publicclassCircleArea{
publicstaticvoidmain(String[]args){
intradius=0;
System.out.println("Pleaseenterradiusofacircle");
try
{
//gettheradiusfrom console
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
radius=Integer.parseInt(br.readLine());
}
//ifinvalidvaluewasentered
catch(NumberFormatExceptionne)
{
System.out.println("Invalidradiusvalue"+ne);
System.exit(0);
}
catch(IOExceptionioe)
{
System.out.println("IOError:"+ioe);
System.exit(0);
}
/*
*Areaofacircleis
*pi*r*r
*whererisaradiusofacircle.
*/
//NOTE:useMath.PIconstanttogetvalueofpi
doublearea=Math.PI*radius*radius;
System.out.println("Areaofacircleis"+area);
}
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Output:
Pleaseenterradiusofacircle
19
Areaofacircleis1134.1149479459152
AreaofRectangle:
Program:
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
publicclassRectArea{
publicstaticvoidmain(String[]args){
intwidth=0;
intlength=0;
try
{
//readthelengthfrom console
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Pleaseenterlengthofarectangle");
length=Integer.parseInt(br.readLine());
//readthewidthfrom console
System.out.println("Pleaseenterwidthofarectangle");
width=Integer.parseInt(br.readLine());
}
//ifinvalidvaluewasentered
catch(NumberFormatExceptionne)
{
System.out.println("Invalidvalue"+ne);
System.exit(0);
}
catch(IOExceptionioe)
{
System.out.println("IOError:"+ioe);
System.exit(0);
}
/*
*Areaofarectangleis
*length*width
*/
intarea=length*width;
System.out.println("Areaofarectangleis"+area);
}
}
Output:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Pleaseenterlengthofarectangle
10
Pleaseenterwidthofarectangle
15
Areaofarectangleis150
BitwiseAddition:
Program:
importjava.util.Scanner;
publicclassBitwise_Addition
{
staticintadd(intx,inty)
{
intcarry;
while(y!=0){
carry=x&y;
x=x^y;
y=carry<<1;
}
returnx;
}
publicstaticvoidmain(Stringargs[])
{
Scannerinput=newScanner(System.in);
System.out.println("Enterthenumberstobeadded:");
intx=input.nextInt();
inty=input.nextInt();
System.out.println("TheSummationis:"+add(x,y));
input.close();
}
}
Output:
Enterthenumberstobeadded:
15
16
TheSummationis:31
SimpleInterest:
Program:
publicclassSimpleInterest{
publicstaticvoidmain(Stringargs[]){
//creatingscannertoacceptprinciple,rateandtimeinputform user
Scannerscanner=newScanner(System.in);
System.out.println("WelcomeinJavaprogram tocalculateSimpleinterest");
System.err.println("Pleaseenterprincipleamount:");
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
floatamount=scanner.nextFloat();
System.err.println("Entertimeinyears:");
floattime=scanner.nextFloat();
System.out.println("Enterrateannually:");
floatrate=scanner.nextFloat();
floatinterest=simpleInterest(amount,rate,time);
System.out.println("Simpleinterestedcalculatebyprogram is:"+interest);
}
publicstaticfloatsimpleInterest(floatprinciple,floatrate,floattime){
floatinterest=(principle*rate*time)/100;
returninterest;
}
}
Output:
Pleaseenterprincipleamount:
1000
Entertimeinyears:
1
Enterrateannually:
7
Simpleinterestedcalculatebyprogram is:70.0
CalculatePercentage:
Program:
importjava.util.Scanner;
publicclassPercentageCalculator
{
publicstaticvoidmain(String[]args)
{
doublex=0;
doubley=0;
Scannerscanner=newScanner(System.in);
System.out.println("Enterthevalueofx:");
x=scanner.nextDouble();
System.out.println("Enterthevalueofy:");
y=scanner.nextDouble();
System.out.println();
System.out.println("Calculatingpercentage:(x%ofy):");
System.out.println(x+"%of"+y+"is"+result);
System.out.println();
}
}
Output:
Enterthevalueofx:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
34
Enterthevalueofy:
200
Calculatingpercentage:(x%ofy):
34%of200is68.0
GCD&LCM:
Program:
importjava.util.Scanner;
publicclassGCD_LCM {
staticintgcd(intx,inty){
intr=0,a,b;
a=(x>y)?x:y;//aisgreaternumber
b=(x<y)?x:y;//bissmallernumber
r=b;
while(a%b!=0){
r=a%b;
a=b;
b=r;
}
returnr;
}
staticintlcm(intx,inty){
inta;
a=(x>y)?x:y;//aisgreaternumber
while(true){
if(a%x==0&&a%y==0)
returna;
++a;
}
}
publicstaticvoidmain(Stringargs[])
{
Scannerinput=newScanner(System.in);
System.out.println("Enterthetwonumbers:");
intx=input.nextInt();
inty=input.nextInt();
System.out.println("TheGCDoftwonumbersis:"+gcd(x,y));
System.out.println("TheLCM oftwonumbersis:"+lcm(x,y));
input.close();
}
}
Output:
Enterthetwonumbers:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
15
25
TheGCDoftwonumbersis:5
TheLCM oftwonumbersis:75
Enterthetwonumbers:
5
8
TheGCDoftwonumbersis:1
TheLCM oftwonumbersis:40
LeapYear:
Program:
publicclassLeapYear{
publicstaticvoidmain(String[]args){
//yearwewanttocheck
intyear=2004;
//ifyearisdivisibleby4,itisaleapyear
if((year%400==0)||((year%4==0)&&(year%100!=0)))
System.out.println("Year"+year+"isaleapyear");
else
System.out.println("Year"+year+"isnotaleapyear");
}
}
Output:
Year2004isaleapyear
PrintTables:
Program:
importjava.util.Scanner;
classMultiplicationTable
{
publicstaticvoidmain(Stringargs[])
{
intn,c;
System.out.println("Enteranintegertoprintit'smultiplicationtable");
Scannerin=newScanner(System.in);
n=in.nextInt();
System.out.println("Multiplicationtableof"+n+"is:-");
for(c=1;c<=10;c++)
System.out.println(n+"*"+c+"="+(n*c));
}
}
Output:
Enteranintegertoprintit'smultiplicationtable
9
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Multiplicationtableof9is:
9*1=9
9*2=18
9*3=27
9*4=36
9*5=45
9*6=54
9*7=63
9*8=72
9*9=81
9*10=90
FindArmstrongNumber:
Program:
importjava.util.Scanner;
classArmstrongNumber
{
publicstaticvoidmain(Stringargs[])
{
intn,sum =0,temp,remainder,digits=0;
Scannerin=newScanner(System.in);
System.out.println("InputanumbertocheckifitisanArmstrongnumber");
n=in.nextInt();
temp=n;
//Countnumberofdigits
while(temp!=0){
digits++;
temp=temp/10;
}
temp=n;
while(temp!=0){
remainder=temp%10;
sum =sum +power(remainder,digits);
temp=temp/10;
}
if(n==sum)
System.out.println(n+"isanArmstrongnumber.");
else
System.out.println(n+"isnotanArmstrongnumber.");
}
staticintpower(intn,intr){
intc,p=1;
for(c=1;c<=r;c++)
p=p*n;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
returnp;
}
}
Output:
InputanumbertocheckifitisanArmstrongnumber
9926315
9926315isanArmstrongnumber.
InputanumbertocheckifitisanArmstrongnumber
15781
45781isnotanArmstrongnumber.
Swappingtwono:
Program:
importjava.util.Scanner;
classSwapNumbers
{
publicstaticvoidmain(Stringargs[])
{
intx,y,temp;
System.out.println("Enterxandy");
Scannerin=newScanner(System.in);
x=in.nextInt();
y=in.nextInt();
System.out.println("BeforeSwapping\nx="+x+"\ny="+y);
temp=x;
x=y;
y=temp;
System.out.println("AfterSwapping\nx="+x+"\ny="+y);
}
}
Output:
Enterxandy
4
5
BeforeSwapping
x=4
y=5
AfterSwapping
x=5
y=4
Swappingwithout3rdvariable:
Program:
importjava.util.Scanner;
classSwapNumbers
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
{
publicstaticvoidmain(Stringargs[])
{
intx,y;
System.out.println("Enterxandy");
Scannerin=newScanner(System.in);
x=in.nextInt();
y=in.nextInt();
System.out.println("BeforeSwapping\nx="+x+"\ny="+y);
x=x+y;
y=x-y;
x=x-y;
System.out.println("AfterSwapping\nx="+x+"\ny="+y);
}
}
Output:
Enterxandy
4
5
BeforeSwapping
x=4
y=5
AfterSwapping
x=5
y=4
FloydTriangle:
Program:
importjava.util.Scanner;
classFloydTriangle
{
publicstaticvoidmain(Stringargs[])
{
intn,num =1,c,d;
Scannerin=newScanner(System.in);
System.out.println("Enterthenumberofrowsoffloyd'striangleyouwant");
n=in.nextInt();
System.out.println("Floyd'striangle:-");
for(c=1;c<=n;c++)
{
for(d=1;d<=c;d++)
{
System.out.print(num+"");
num++;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
System.out.println();
}
}
}
Output:
EnterthenumberofrowsofFloyd'striangleyouwant
5
Floyd'striang1e:-
1
23
456
78910
1112131415
PascalTriangle:
Program:
publicclassPascalsTriangle
{
publicstaticvoidmain(String[]args)
{
int[][]triangle=newint[5][];
fillIn(triangle);
print(triangle);
}
publicstaticvoidfillIn(int[][]triangle){
for(inti=0;i<triangle.length;i++){
triangle[i]=newint[i+1];
triangle[i][0]=1;
triangle[i][i]=1;
for(intj=1;j<i;j++){
triangle[i][j]=triangle[i-1][j-1]
+triangle[i-1][j];
}
}
}
publicstaticvoidprint(int[][]triangle){
for(inti=0;i<triangle.length;i++){
for(intj=0;j<triangle[i].length;j++){
System.out.print(triangle[i][j]+"");
}
System.out.println();
}
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
Output:
1
11
121
1331
14641
BinarytoDecimal:
Program:
importjava.util.Scanner;
publicclassBinary_Decimal{
Scannerscan;
intnum;
voidgetVal(){
System.out.println("BinarytoDecimal");
scan=newScanner(System.in);
System.out.println("\nEnterthenumber:");
num =Integer.parseInt(scan.nextLine(),2);
}
voidconvert(){
Stringdecimal=Integer.toString(num);
System.out.println("DecimalValueis:"+decimal);
}
}
classMainClass{
publicstaticvoidmain(Stringargs[]){
Binary_Decimalobj=newBinary_Decimal();
obj.getVal();
obj.convert();
}
}
Output:
BinarytoDecimal
Enterthenumber:
1010
DecimalValueis:10
DecimaltoBinary:
Program:
importjava.util.Scanner;
publicclassDecimalToBinary{
publicStringtoBinary(intn){
if(n==0){
return"0";
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
Stringbinary="";
while(n>0){
intrem =n%2;
binary=rem +binary;
n=n/2;
}
returnbinary;
}
publicstaticvoidmain(String[]args){
Scannerscanner=newScanner(System.in);
System.out.print("Enteranumber:");
intdecimal=scanner.nextInt();
DecimalToBinarydtb=newDecimalToBinary();
Stringbinary=dtb.toBinary(decimal);
System.out.println("Thebinaryrepresentationis"+binary);
}
}
Output:
Enteranumber:14
Thebinaryrepresentationis1110
DecimaltoHex:
Program:
importjava.util.Scanner;
publicclassDecimal_Hexa{
Scannerscan;
intnum;
voidgetVal(){
System.out.println("DecimaltoHexaDecimal");
scan=newScanner(System.in);
System.out.println("\nEnterthenumber:");
num =Integer.parseInt(scan.nextLine());
}
voidconvert(){
Stringhexa=Integer.toHexString(num);
System.out.println("HexaDecimalValueis:"+hexa);
}
}
classMainClass{
publicstaticvoidmain(Stringargs[]){
Decimal_Hexaobj=newDecimal_Hexa();
obj.getVal();
obj.convert();
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
}
Output:
DecimaltoHexaDecimal
Enterthenumber:
15
DecimaltoOctal:
Program:
importjava.util.Scanner;
publicclassDecimal_Octal{
Scannerscan;
intnum;
voidgetVal(){
System.out.println("DecimaltoOctal");
scan=newScanner(System.in);
System.out.println("\nEnterthenumber:");
num =Integer.parseInt(scan.nextLine());
}
voidconvert(){
Stringoctal=Integer.toOctalString(num);
System.out.println("OctalValueis:"+octal);
}
}
classMainClass{
publicstaticvoidmain(Stringargs[]){
Decimal_Octalobj=newDecimal_Octal();
obj.getVal();
obj.convert();
}
}
Output:
DecimaltoOctal
Enterthenumber:
148
OctalValueis:224
HextoDecimal:
Program:
importjava.util.Scanner;
publicclassHexa_Decimal{
Scannerscan;
intnum;
voidgetVal(){
System.out.println("HexaDecimaltoDecimal");
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
scan=newScanner(System.in);
System.out.println("\nEnterthenumber:");
num =Integer.parseInt(scan.nextLine(),16);
}
voidconvert(){
Stringdecimal=Integer.toString(num);
System.out.println("DecimalValueis:"+decimal);
}
}
classMainClass{
publicstaticvoidmain(Stringargs[]){
Hexa_Decimalobj=newHexa_Decimal();
obj.getVal();
obj.convert();
}
}
Output:
HexaDecimaltoDecimal
Enterthenumber:
20
DecimalValueis:32
OctaltoDecimal:
Program:
importjava.util.Scanner;
publicclassOctal_Decimal{
Scannerscan;
intnum;
voidgetVal(){
System.out.println("OctaltoDecimal");
scan=newScanner(System.in);
System.out.println("\nEnterthenumber:");
num =Integer.parseInt(scan.nextLine(),8);
}
voidconvert(){
Stringdecimal=Integer.toString(num);
System.out.println("DecimalValueis:"+decimal);
}
}
classMainClass{
publicstaticvoidmain(Stringargs[]){
Octal_Decimalobj=newOctal_Decimal();
obj.getVal();
obj.convert();
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
}
Output:
OctaltoDecimal
Enterthenumber:
10
DecimalValueis:8
ConstructorExample:
Program:
classProgramming{
//constructormethod
Programming(){
System.out.println("Constructormethodcalled.");
}
publicstaticvoidmain(String[]args){
Programmingobject=newProgramming();//creatingobject
}
}
Output:
Constructormethodcalled.
ThreadExample:
Program:
/*
TocreateathreadusingRunnable,aclassmustimplementJavaRunnableinterface.
*/
publicclassThreadExampleimplementsRunnable{
publicvoidrun(){
for(inti=0;i<5;i++){
System.out.println("ChildThread:"+i);
try{
Thread.sleep(50);
}
catch(InterruptedExceptionie){
System.out.println("Childthreadinterrupted!"+ie);
}
}
System.out.println("Childthreadfinished!");
}
publicstaticvoidmain(String[]args){
Threadt=newThread(newCreateThreadRunnableExample(),"MyThread");
t.start();
for(inti=0;i<5;i++){
System.out.println("Mainthread:"+i);
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
try{
Thread.sleep(100);
}
catch(InterruptedExceptionie){
System.out.println("Childthreadinterrupted!"+ie);
}
}
System.out.println("Mainthreadfinished!");
}
}
Output:
Mainthread:0
ChildThread:0
ChildThread:1
Mainthread:1
Mainthread:2
ChildThread:2
ChildThread:3
Mainthread:3
Mainthread:4
ChildThread:4
Childthreadfinished!
Mainthreadfinished!
FinallyExample:
Program:
publicclassFinallyExample{
publicstaticvoidmain(String[]argv){
newFinallyExample().doTheWork();
}
publicvoiddoTheWork(){
Objecto=null;
for(inti=0;i7lt;5;i++){
try{
o=makeObj(i);
}
catch(IllegalArgumentExceptione){
System.err.println
("Error:("+e.getMessage()+").");
return;
}
finally{
System.err.println("Alldone");
if(o==null)
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
System.exit(0);
}
System.out.println(o);
}
}
publicObjectmakeObj(inttype)
throwsIllegalArgumentException{
if(type==1)
thrownewIllegalArgumentException
("Don'tliketype"+type);
returnnewObject();
}
}
Output:
Alldone
java.lang.Object@1b90b39
Error:(Don'tliketype1).
Alldone
UserDefinedException:
Program:
classWrongInputExceptionextendsException{
WrongInputException(Strings){
super(s);
}
}
classInput{
voidmethod()throwsWrongInputException{
thrownewWrongInputException("Wronginput");
}
}
classTestInput{
publicstaticvoidmain(String[]args){
try{
newInput().method();
}
catch(WrongInputExceptionwie){
System.out.println(wie.getMessage());
}
}
}
Output:
Wronginput
PrintAlphabets:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Program:
classAlphabets
{
publicstaticvoidmain(Stringargs[])
{
charch;
for(ch='a';ch<='z';ch++)
System.out.println(ch);
}
}
Output:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
PalindromeString:
Program:
importjava.util.*;
classPalindrome
{
publicstaticvoidmain(Stringargs[])
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
{
Stringoriginal,reverse="";
Scannerin=newScanner(System.in);
System.out.println("Enterastringtocheckifitisapalindrome");
original=in.nextLine();
intlength=original.length();
for(inti=length-1;i>=0;i--)
reverse=reverse+original.charAt(i);
if(original.equals(reverse))
System.out.println("Enteredstringisapalindrome.");
else
System.out.println("Enteredstringisnotapalindrome.");
}
}
Output:
Enterastringtocheckifitisapalindrome
madam
Enteredstringisapalindrome.
Enterastringtocheckifitisapalindrome
akshay
Enteredstringisnotapalindrome.
StringChangeCase:
Program:
publicclassStringChangeCase{
publicstaticvoidmain(String[]args){
Stringstr="HelloWorld";
StringstrLower=str.toLowerCase();
StringstrUpper=str.toUpperCase();
System.out.println("OriginalString:"+str);
System.out.println("Stringchangedtolowercase:"+strLower);
System.out.println("Stringchangedtouppercase:"+strUpper);
}
}
Output:
OriginalString:HelloWorld
Stringchangedtolowercase:helloworld
Stringchangedtouppercase:HELLOWORLD
StringLength:
Program:
publicclassStringLengthExample{
publicstaticvoidmain(String[]args){
//declaretheStringobject
Stringstr="HelloWorld";
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
//length()methodofStringreturnsthelengthofaString.
intlength=str.length();
System.out.println("LengthofaStringis:"+length);
}
}
Output:
LengthofaStringis:11
StringConcat:
Program:
publicclassStringConcat{
publicstaticvoidmain(Stringargs[]){
Stringstr1="Hello";
Stringstr2="World";
//1.Using+operator
Stringstr3=str1+str2;
System.out.println("Stringconcatusing+operator:"+str3);
//2.UsingString.concat()method
Stringstr4=str1.concat(str2);
System.out.println("StringconcatusingStringconcatmethod:"+str4);
//3.UsingStringBuffer.appendmethod
Stringstr5=newStringBuffer().append(str1).append(str2).toString();
System.out.println("StringconcatusingStringBufferappendmethod:"+str5);
}
}
Output:
Stringconcatusing+operator:HelloWorld
StringconcatusingStringconcatmethod:HelloWorld
StringconcatusingStringBufferappendmethod:HelloWorld
StringReverse:
Program:
publicclassStringReverse{
publicstaticvoidmain(Stringargs[]){
StringstrOriginal="HelloWorld";
System.out.println("OriginalString:"+strOriginal);
strOriginal=newStringBuffer(strOriginal).reverse().toString();
System.out.println("ReversedString:"+strOriginal);
}
}
Output:
OriginalString:HelloWorld
ReversedString:dlroW olleH
StringTrim:
Program:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
publicclassRemoveSpace{
publicstaticvoidmain(String[]args){
Stringstr="StringTrim Example";
StringstrTrimmed=str.trim();
System.out.println("OriginalStringis:"+str);
System.out.println("RemovedLeadingandtrailingspace");
System.out.println("NewStringis:"+strTrimmed);
}
}
Output:
OriginalStringis: StringTrim Example
RemovedLeadingandtrailingspace
NewStringis:StringTrim Example
RemoveVowels:
Program:
importjava.util.*;
classRemoveVowels
{
publicstaticvoidmain(Stringargs[])
{
System.out.print("PleaseEntertheSentence:");
Scanners=newScanner(System.in);
Stringword=s.nextLine();
char[]c=word.toCharArray();
charcc[]=newchar[80];
intj=0;
for(inti=0;i<c.length;i++)
{
if(c[i]=='a'||c[i]=='e'||c[i]=='i'||c[i]=='0'||c[i]=='u')
{
continue;
}
else
{
cc[j]=c[i];
j++;
}
}
System.out.print("AfterRemoveingVowelsfrom aSentence:");
System.out.print(cc);
}
}
Output:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
PleaseentertheSentence:
AkshayBhange
AfterRemoveingVowelsfrom aSentence:
kshybhng
StringRemoveChar:
Program:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
Stringstr="thisisJava";
System.out.println(removeCharAt(str,3));
}
publicstaticStringremoveCharAt(Strings,intpos){
returns.substring(0,pos)+s.substring(pos+1);
}
}
Output:
thiisJava
ReverseStringArray:
Program:
importjava.util.Collections;
importjava.util.List;
importjava.util.Arrays;
publicclassReverseStringArray{
publicstaticvoidmain(Stringargs[]){
String[]strDays=newString[]{"Sunday","Monday","Tuesday","Wednesday"};
List<String>list=Arrays.asList(strDays);
//reversethelistusingCollections.reversemethod
Collections.reverse(list);
strDays=(String[])list.toArray();
System.out.println("Stringarrayreversed");
for(inti=0;i<strDays.length;i++){
System.out.println(strDays[i]);
}
}
}
Output:
Stringarrayreversed
Wednesday
Tuesday
Monday
Sunday
SortStringArray:
Program:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
importjava.util.Arrays;
publicclassSortStringArray{
publicstaticvoidmain(Stringargs[]){
String[]strNames=newString[]{"Jay","akshay","Chiru","vikas","Mohan","raj"};
//sortStringarrayusingsortmethod
Arrays.sort(strNames);
System.out.println("Stringarraysorted(casesensitive)");
for(inti=0;i<strNames.length;i++){
System.out.println(strNames[i]);
}
/*
TosortanarrayofStringsirrespectiveofcase,useArrays.sort(String[]strArray,
String.CASE_INSENSITIVE_ORDER)methodinstead.
*/
}
}
Output:
Stringarraysorted(casesensitive)
Chiru
Jay
Mohan
akshay
raj
vikas
StringtoCharArray:
Program:
publicclassStringToCharArray{
publicstaticvoidmain(Stringargs[]){
StringstrOrig="HelloWorld";
char[]stringArray;
//convertstringintoarrayusingtoCharArray()methodofstringclass
stringArray=strOrig.toCharArray();
for(intindex=0;index<stringArray.length;index++)
System.out.print(stringArray[index]);
}
}
Output:
HelloWorld
CharArraytoString:
Program:
publicclassCharArrayToString{
publicstaticvoidmain(Stringargs[]){
char[]charArray=newchar[]{'J','a','v','a'};
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
/*
ToconvertchararraytoStringinJava,useString(Char[]ch)constructorofJavaStringclass.
*/
Stringstr=newString(charArray);
System.out.println("ChararrayconvertedtoString:"+str);
}
}
Output:
ChararrayconvertedtoString:Java
LargestSmallest:
Program:
publicclassLargestSmallest{
publicstaticvoidmain(String[]args){
//arrayof10numbers
intnumbers[]=newint[]{32,43,53,54,32,65,63,98,43,23};
//assignfirstelementofanarraytolargestandsmallest
intsmallest=numbers[0];
intlargetst=numbers[0];
for(inti=1;i<numbers.length;i++)
{
if(numbers[i]>largetst)
largetst=numbers[i];
elseif(numbers[i]<smallest)
smallest=numbers[i];
}
System.out.println("LargestNumberis:"+largetst);
System.out.println("SmallestNumberis:"+smallest);
}
}
Output:
LargestNumberis:98
SmallestNumberis:23
Averageofarray:
Program:
publicclassArrayAverage{
publicstaticvoidmain(String[]args){
//defineanarray
int[]numbers=newint[]{10,20,15,25,16,60,100};
//calculatesum ofallarrayelements
intsum =0;
for(inti=0;i<numbers.length;i++)
sum =sum +numbers[i];
//calculateaveragevalue
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
doubleaverage=sum /numbers.length;
System.out.println("Averagevalueofarrayelementsis:"+average);
}
}
Output:
Averagevalueofarrayelementsis:35.0
ArrayCopy:
Program:
classArrayCopy
{
publicstaticvoidmain(Stringargs[])
{
intA1[]={10,20,30,40,50,60,70,80,90,100};
intA2[]={1,2,3,4,5,6,7,8,9,10};
System.out.println("ThefirstArrayis:");
for(inti=0;i<10;i++)
System.out.print(A1[i]+"");
System.out.println("\nTheSecondArrayis:");
for(inti=0;i<10;i++)
System.out.print(A2[i]+"");
System.arraycopy(A1,5,A2,5,5);
//Copyinglast5elementsofA1toA2
System.out.println("\nThesecondArrayaftercallingarraycopy():");
for(inti=0;i<10;i++)
System.out.print(A2[i]+"");
}
}
Output:
ThefirstArrayis:
102030405060708090100
ThesecondArrayis:
12345678910
ThesecondArrayaftercallingarraycopy():
1234560708090100
Deleteelementfrom Array:
Program:
publicclassDeleteArray{
publicstaticvoidmain(String[]arguments){
intarg[]={5,6,8,9,10};
intpos=3;
for(intk=0;k<arg.length;k++){
System.out.println(arg[k]);
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
for(inti=0;i<arg.length;i++){
if(pos==i){
for(intj=i+1;i<arg.length-1;j++){
arg[i]=arg[j];
i++;
}
}
}
System.out.println("TheoutputofArrayAfterDelete");
for(inti=0;i<arg.length-1;i++){
System.out.println(arg[i]);
}
}
}
Output:
5
6
8
9
10
TheoutputofArrayAfterDelete
5
6
8
10
2DArrayExample:
Program:
classTwoDArray
{
publicstaticvoidmain(Stringargs[])
{
inttwoD[][]=newint[4][5];
intk=0,i,j;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
{
twoD[i][j]=k;
k++;
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
System.out.print(twoD[i][j]+"");
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
System.out.println();
}
}
}
Output:
01234
56789
1011121314
1516171819
MatrixMultiplication:
Program:
importjava.util.Scanner;
publicclassMatixMultiplication{
publicstaticvoidmain(Stringargs[]){
intn;
Scannerinput=newScanner(System.in);
System.out.println("Enterthebaseofsquaredmatrices");
n=input.nextInt();
int[][]a=newint[n][n];
int[][]b=newint[n][n];
int[][]c=newint[n][n];
System.out.println("Entertheelementsof1stmartixrowwise\n");
for(inti=0;i<n;i++){
for(intj=0;j<n;j++){
a[i][j]=input.nextInt();
}
}
System.out.println("Entertheelementsof2ndmartixrowwise\n");
for(inti=0;i<n;i++){
for(intj=0;j<n;j++){
b[i][j]=input.nextInt();
}
}
System.out.println("Multiplyingthematrices...");
for(inti=0;i<n;i++){
for(intj=0;j<n;j++){
for(intk=0;k<n;k++){
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
System.out.println("Theproductis:");
for(inti=0;i<n;i++){
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
for(intj=0;j<n;j++){
System.out.print(c[i][j]+"");
}
System.out.println();
}
input.close();
}
}
Output:
Enterthebaseofsquaredmatrices:
3
Entertheelementsof1stmartixrowwise:
123
456
789
Entertheelementsof2ndmartixrowwise:
234
567
891
Multiplyingthematrices...
Theproductis:
364221
819657
12615093
MatrixTranspose:
Program:
importjava.util.Scanner;
classTransposeAMatrix
{
publicstaticvoidmain(Stringargs[])
{
intm,n,c,d;
Scannerin=newScanner(System.in);
System.out.println("Enterthenumberofrowsandcolumnsofmatrix");
m =in.nextInt();
n=in.nextInt();
intmatrix[][]=newint[m][n];
System.out.println("Entertheelementsofmatrix");
for(c=0;c<m ;c++)
for(d=0;d<n;d++)
matrix[c][d]=in.nextInt();
inttranspose[][]=newint[n][m];
for(c=0;c<m ;c++)
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
{
for(d=0;d<n;d++)
transpose[d][c]=matrix[c][d];
}
System.out.println("Transposeofenteredmatrix:-");
for(c=0;c<n;c++)
{
for(d=0;d<m ;d++)
System.out.print(transpose[c][d]+"\t");
System.out.print("\n");
}
}
}
Output:
Enterthenumberofrowsandcolumnofmatrix:
23
Entertheelementsofmatrix:
123
456
Transposeofenteredmatrix:
14
25
36
SparseMatrix:
Program:
importjava.util.Scanner;
publicclassSparsity_Matrix{
publicstaticvoidmain(Stringargs[]){
Scannersc=newScanner(System.in);
System.out.println("Enterthedimensionsofthematrix:");
intm =sc.nextInt();
intn=sc.nextInt();
double[][]mat=newdouble[m][n];
intzeros=0;
System.out.println("Entertheelementsofthematrix:");
for(inti=0;i<m;i++){
for(intj=0;j<n;j++){
mat[i][j]=sc.nextDouble();
if(mat[i][j]==0){
zeros++;
}
}
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
if(zeros>(m*n)/2){
System.out.println("Thematrixisasparsematrix");
}
else{
System.out.println("Thematrixisnotasparsematrix");
}
sc.close();
}
}
Output:
Enterthedimensionsofthematrix:
23
Entertheelementsofthematrix:
100
211
Thematrixisnotasparsematrix
Enterthedimensionsofthematrix:
34
Entertheelementsofthematrix:
1000
0100
0011
Thematrixisasparsematrix
InterfaceExample:
Program:
interfaceInfo{
staticfinalStringlanguage="Java";
publicvoiddisplay();
}
classSimpleimplementsInfo{
publicstaticvoidmain(String[]args){
Simpleobj=newSimple();
obj.display();
}
//Definingmethoddeclaredininterface
publicvoiddisplay(){
System.out.println(language+"isawesome");
}
}
Output:
Javaisawesome
InterfaceExample:
Program:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
interfaceInfo{
staticfinalStringlanguage="Java";
publicvoiddisplay();
}
classSimpleimplementsInfo{
publicstaticvoidmain(String[]args){
Simpleobj=newSimple();
obj.display();
}
//Definingmethoddeclaredininterface
publicvoiddisplay(){
System.out.println(language+"isawesome");
}
}
Output:
Javaisawesome
LinearSearch:
Program:
importjava.util.Scanner;
classLinearSearch
{
publicstaticvoidmain(Stringargs[])
{
intc,n,search,array[];
Scannerin=newScanner(System.in);
System.out.println("Enternumberofelements");
n=in.nextInt();
array=newint[n];
System.out.println("Enter"+n+"integers");
for(c=0;c<n;c++)
array[c]=in.nextInt();
System.out.println("Entervaluetofind");
search=in.nextInt();
for(c=0;c<n;c++)
{
if(array[c]==search)/*Searchingelementispresent*/
{
System.out.println(search+"ispresentatlocation"+(c+1)+".");
break;
}
}
if(c==n)/*Searchingelementisabsent*/
System.out.println(search+"isnotpresentinarray.");
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
}
Output:
Enternumberofelements
7
Enter7integers
656
-486
12231
48
38
2013
Entervaluetofind
2013
2013ispresentatlocation7.
BinarySearch:
Program:
importjava.util.Scanner;
classBinarySearch
{
publicstaticvoidmain(Stringargs[])
{
intc,first,last,middle,n,search,array[];
Scannerin=newScanner(System.in);
System.out.println("Enternumberofelements");
n=in.nextInt();
array=newint[n];
System.out.println("Enter"+n+"integers");
for(c=0;c<n;c++)
array[c]=in.nextInt();
System.out.println("Entervaluetofind");
search=in.nextInt();
first=0;
last=n-1;
middle=(first+last)/2;
while(first<=last)
{
if(array[middle]<search)
first=middle+1;
elseif(array[middle]==search)
{
System.out.println(search+"foundatlocation"+(middle+1)+".");
break;
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
else
last=middle-1;
middle=(first+last)/2;
}
if(first>last)
System.out.println(search+"isnotpresentinthelist.\n");
}
}
Output:
Enternumberofelements
5
Enter5integers
3
8
6
9
5
Entervaluetofind
6
foundatlocation3
BubbleSort:
Program:
importjava.util.Random;
publicclassBubble_Sort{
staticint[]sort(int[]sequence){
//BubbleSort
for(inti=0;i<sequence.length;i++)
for(intj=0;j<sequence.length-1;j++)
if(sequence[j]>sequence[j+1]){
sequence[j]=sequence[j]+sequence[j+1];
sequence[j+1]=sequence[j]-sequence[j+1];
sequence[j]=sequence[j]-sequence[j+1];
}
returnsequence;
}
staticvoidprintSequence(int[]sorted_sequence){
for(inti=0;i<sorted_sequence.length;i++)
System.out.print(sorted_sequence[i]+"");
}
publicstaticvoidmain(Stringargs[])
{
System.out.println("SortingofrandomlygeneratednumbersusingBUBBLESORT");
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Random random =newRandom();
intN=20;
int[]sequence=newint[N];
for(inti=0;i<N;i++)
sequence[i]=Math.abs(random.nextInt(1000));
System.out.println("\nOriginalSequence:");
printSequence(sequence);
System.out.println("\nSortedSequence:");
printSequence(sort(sequence));
}
}
Output:
SortingofrandomlygeneratednumbersusingBUBBLESORT
OriginalSequence:
3076775748832585167635717293216645060538964987706690919518
SortedSequence:
6088166172307325357450518538574676677690706851919932964987
SelectionSort:
Program:
importjava.util.Scanner;
/*ClassSelectionSort*/
publicclassSelectionSort{
/*SelectionSortfunction*/
publicstaticvoidsort(intarr[]){
intN=arr.length;
inti,j,pos,temp;
for(i=0;i<N-1;i++){
pos=i;
for(j=i+1;j<N;j++){
if(arr[j]<arr[pos]){
pos=j;
}
}
/*Swaparr[i]andarr[pos]*/
temp=arr[i];
arr[i]=arr[pos];
arr[pos]=temp;
}
}
/*Mainmethod*/
publicstaticvoidmain(String[]args)
{
Scannerscan=newScanner(System.in);
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
System.out.println("SelectionSortTest\n");
intn,i;
/*Acceptnumberofelements*/
System.out.println("Enternumberofintegerelements");
n=scan.nextInt();
/*Createintegerarrayonnelements*/
intarr[]=newint[n];
/*Acceptelements*/
System.out.println("\nEnter"+n+"integerelements");
for(i=0;i<n;i++)
arr[i]=scan.nextInt();
/*Callmethodsort*/
sort(arr);
/*PrintsortedArray*/
System.out.println("\nElementsaftersorting");
for(i=0;i<n;i++)
System.out.print(arr[i]+"");
System.out.println();
}
}
Output:
SelectionSortTest
Enternumberofintegerelements
20
Enter20integerelements
12346879123145178213253276298301498512633792888912950991
Elementsaftersorting
12346879123145178213253276298301498512633792888912950991
SelectionSort:
Program:
importjava.util.Scanner;
/*ClassSelectionSort*/
publicclassSelectionSort{
/*SelectionSortfunction*/
publicstaticvoidsort(intarr[]){
intN=arr.length;
inti,j,pos,temp;
for(i=0;i<N-1;i++){
pos=i;
for(j=i+1;j<N;j++){
if(arr[j]<arr[pos]){
pos=j;
}
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
}
/*Swaparr[i]andarr[pos]*/
temp=arr[i];
arr[i]=arr[pos];
arr[pos]=temp;
}
}
/*Mainmethod*/
publicstaticvoidmain(String[]args)
{
Scannerscan=newScanner(System.in);
System.out.println("SelectionSortTest\n");
intn,i;
/*Acceptnumberofelements*/
System.out.println("Enternumberofintegerelements");
n=scan.nextInt();
/*Createintegerarrayonnelements*/
intarr[]=newint[n];
/*Acceptelements*/
System.out.println("\nEnter"+n+"integerelements");
for(i=0;i<n;i++)
arr[i]=scan.nextInt();
/*Callmethodsort*/
sort(arr);
/*PrintsortedArray*/
System.out.println("\nElementsaftersorting");
for(i=0;i<n;i++)
System.out.print(arr[i]+"");
System.out.println();
}
}
Output:
SelectionSortTest
Enternumberofintegerelements
20
Enter20integerelements
12346879123145178213253276298301498512633792888912950991
Elementsaftersorting
12346879123145178213253276298301498512633792888912950991
InsertionSort:
Program:
importjava.util.Scanner;
/*ClassInsertionSort*/
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
publicclassInsertionSort{
/*InsertionSortfunction*/
publicstaticvoidsort(intarr[]){
intN=arr.length;
inti,j,temp;
for(i=1;i<N;i++){
j=i;
temp=arr[i];
while(j>0&&temp<arr[j-1]){
arr[j]=arr[j-1];
j=j-1;
}
arr[j]=temp;
}
}
/*Mainmethod*/
publicstaticvoidmain(String[]args){
Scannerscan=newScanner(System.in);
System.out.println("InsertionSortTest\n");
intn,i;
/*Acceptnumberofelements*/
System.out.println("Enternumberofintegerelements");
n=scan.nextInt();
/*Createintegerarrayonnelements*/
intarr[]=newint[n];
/*Acceptelements*/
System.out.println("\nEnter"+n+"integerelements");
for(i=0;i<n;i++)
arr[i]=scan.nextInt();
/*Callmethodsort*/
sort(arr);
/*PrintsortedArray*/
System.out.println("\nElementsaftersorting");
for(i=0;i<n;i++)
System.out.print(arr[i]+"");
System.out.println();
}
}
Output:
InsertionSortTest
Enternumberofintegerelements
20
Enter20integerelements
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
5413523751576234928138463112837481245462448510240
Elementsaftersorting
0161323245454758412413523448557663174892810241283
QuickSort:
Program:
importjava.util.Scanner;
/**ClassQuickSort**/
publicclassQuickSort{
/**QuickSortfunction**/
publicstaticvoidsort(int[]arr){
quickSort(arr,0,arr.length-1);
}
/**Quicksortfunction**/
publicstaticvoidquickSort(intarr[],intlow,inthigh){
inti=low,j=high;
inttemp;
intpivot=arr[(low+high)/2];
/**partition**/
while(i<=j){
while(arr[i]<pivot)
i++;
while(arr[j]>pivot)
j--;
if(i<=j){
/**swap**/
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
}
/**recursivelysortlowerhalf**/
if(low<j)
quickSort(arr,low,j);
/**recursivelysortupperhalf**/
if(i<high)
quickSort(arr,i,high);
}
/**Mainmethod**/
publicstaticvoidmain(String[]args)
{
Scannerscan=newScanner(System.in);
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
System.out.println("QuickSortTest\n");
intn,i;
/**Acceptnumberofelements**/
System.out.println("Enternumberofintegerelements");
n=scan.nextInt();
/**Createarrayofnelements**/
intarr[]=newint[n];
/**Acceptelements**/
System.out.println("\nEnter"+n+"integerelements");
for(i=0;i<n;i++)
arr[i]=scan.nextInt();
/**Callmethodsort**/
sort(arr);
/**PrintsortedArray**/
System.out.println("\nElementsaftersorting");
for(i=0;i<n;i++)
System.out.print(arr[i]+"");
System.out.println();
}
}
Output:
QuickSortTest
Enternumberofintegerelements
10
Enter10integerelements
877567345687646726934987614567
Elementsaftersorting
126467567876877934345645679876
MergeSort:
Program:
importjava.util.Scanner;
/*ClassMergeSort*/
publicclassMergeSort{
/*MergeSortfunction*/
publicstaticvoidsort(int[]a,intlow,inthigh){
intN=high-low;
if(N<=1)
return;
intmid=low+N/2;
//recursivelysort
sort(a,low,mid);
sort(a,mid,high);
//mergetwosortedsubarrays
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
int[]temp=newint[N];
inti=low,j=mid;
for(intk=0;k<N;k++){
if(i==mid)
temp[k]=a[j++];
elseif(j==high)
temp[k]=a[i++];
elseif(a[j]<a[i])
temp[k]=a[j++];
else
temp[k]=a[i++];
}
for(intk=0;k<N;k++)
a[low+k]=temp[k];
}
/*Mainmethod*/
publicstaticvoidmain(String[]args)
{
Scannerscan=newScanner(System.in);
System.out.println("MergeSortTest\n");
intn,i;
/*Acceptnumberofelements*/
System.out.println("Enternumberofintegerelements");
n=scan.nextInt();
/*Createarrayofnelements*/
intarr[]=newint[n];
/*Acceptelements*/
System.out.println("\nEnter"+n+"integerelements");
for(i=0;i<n;i++)
arr[i]=scan.nextInt();
/*Callmethodsort*/
sort(arr,0,n);
/*PrintsortedArray*/
System.out.println("\nElementsaftersorting");
for(i=0;i<n;i++)
System.out.print(arr[i]+"");
System.out.println();
}
}
Output:
MergeSortTest
Enternumberofintegerelements
20
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Enter20integerelements
605514864711232664674357161695111508262879832849457357185974
Elementsaftersorting
111161185232262357357457508514605664674695711832849864879974
MultipleCatch:
Program:
publicclassMain{
publicstaticvoidmain(Stringargs[]){
intarray[]={20,20,40};
intnum1=15,num2=0;
intresult=0;
try{
result=num1/num2;
System.out.println("Theresultis"+result);
for(inti=2;i7gt;=0;i--){
System.out.println
("Thevalueofarrayis"+array[i]);
}
}
catch(ArrayIndexOutOfBoundsExceptione){
System.out.println
("Error:.ArrayisoutofBounds"+e);
}
catch(ArithmeticExceptione){
System.out.println
("Can'tbedividedbyZero"+e);
}
}
}
Output:
Can'tbedividedbyZerojava.lang.ArithmeticException:/byzero
CreateDirectory:
Program:
importjava.io.*;
publicclassCreateDirectory
{
publicstaticvoidmain(String[]args)
{
Filedir=newFile("C://FileIO//DemoDirectory");
booleanisDirectoryCreated=dir.mkdir();
if(isDirectoryCreated)
System.out.println("Directorycreatedsuccessfully");
else
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
System.out.println("Directorywasnotcreatedsuccessfully");
}
}
Output:
Directorycreatedsuccessfully
ListContentsofDir:
Program:
importjava.io.*;
publicclassListOfDirectory{
publicstaticvoidmain(String[]args){
Filefile=newFile("C://FileIO");
String[]files=file.list();
System.out.println("Listingcontentsof"+file.getPath());
for(inti=0;i<files.length;i++)
{
System.out.println(files[i]);
}
}
}
Output:
demo.java
demo.class
RenameFIle-Dir:
Program:
importjava.io.*;
publicclassRenameFile{
publicstaticvoidmain(String[]args){
FileoldName=newFile("C://FileIO//source.txt");
FilenewName=newFile("C://FileIO//destination.txt");
booleanisFileRenamed=oldName.renameTo(newName);
if(isFileRenamed)
System.out.println("Filehasbeenrenamed");
else
System.out.println("Errorrenamingthefile");
}
}
Output:
Filehasbeenrenamed
DeleteDirectory:
Program:
importjava.io.*;
publicclassDeleteFileOrDirectory{
publicstaticvoidmain(String[]args){
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
Filefile=newFile("C://FileIO/DeleteDemo.txt");
booleanblnDeleted=file.delete();
System.out.println("Wasfiledeleted?:"+blnDeleted);
/*
Pleasenotethatdeletemethodreturnsfalseifthefiledidnotexistsorthedirectorywasnot
empty.
*/
}
}
Output:
Wasfiledeleted?:true
DateTime:
Program:
importjava.util.*;
classGetCurrentDateAndTime
{
publicstaticvoidmain(Stringargs[])
{
intday,month,year;
intsecond,minute,hour;
GregorianCalendardate=newGregorianCalendar();
day=date.get(Calendar.DAY_OF_MONTH);
month=date.get(Calendar.MONTH);
year=date.get(Calendar.YEAR);
second=date.get(Calendar.SECOND);
minute=date.get(Calendar.MINUTE);
hour=date.get(Calendar.HOUR);
System.out.println("Currentdateis"+day+"/"+(month+1)+"/"+year);
System.out.println("Currenttimeis"+hour+":"+minute+":"+second);
}
}
Output:
Currentdateis5/2/2015
Currenttimeis7:52:3
DatetoString:
Program:
importjava.text.DateFormat;
importjava.text.SimpleDateFormat;
importjava.util.Date;
publicclassDateToString{
publicstaticvoidmain(Stringargs[]){
Datedate=newDate();
/*Toconvertjava.util.DatetoString,useSimpleDateFormatclass.*/
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
DateFormatdateFormat=newSimpleDateFormat("yyyy-mm-ddhh:mm:ss");
//toconvertDatetoString,useformatmethodofSimpleDateFormatclass.
StringstrDate=dateFormat.format(date);
System.out.println("DateconvertedtoString:"+strDate);
}
}
Output:
DateconvertedtoString:2015-3-113:17:50
Random Functions:
Program:
importjava.util.Random;
importjava.util.UUID;
publicclassRand_and_Srand{
publicstaticvoidmain(Stringargs[])
{
System.out.println("Thenumbersusingrand");
for(inti=0;i<5;i++)
{
Random rand=newRandom();
System.out.println(Math.abs(rand.nextInt()));
}
System.out.println("Thenumbersusingsrand");
for(inti=0;i<5;i++)
{
System.out.println(Math.abs(UUID.randomUUID().getMostSignificantBits()));
}
}
}
Output:
Thenumbersusingrand
1339557437
636169175
1207287888
1539694038
1040189301
Thenumbersusingsrand
301709257092546335
8798470719933102847
3480203219570178904
3272351410737399038
2158529096808811162
Random Numbers:
Program:
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
importjava.util.*;
classRandomNumbers{
publicstaticvoidmain(String[]args){
intc;
Random t=newRandom();
//random integersin[0,100]
for(c=1;c<=10;c++){
System.out.println(t.nextInt(100));
}
}
}
Output:
62
47
60
17
52
59
24
47
2
21
OpenNotepad:
Program:
importjava.util.*;
importjava.io.*;
classNotepad{
publicstaticvoidmain(String[]args){
Runtimers=Runtime.getRuntime();
try{
rs.exec("notepad");
}
catch(IOExceptione){
System.out.println(e);
}
}
}
Output:
Nooutputforthisprogram
DisplayIPAddress:
Program:
importjava.net.InetAddress;
classIPAddress
MURAMUZI ADAM
BSTE MAKERERE UNIVERSITY
STUDYING TO CHANGE THE SITUATION
{
publicstaticvoidmain(Stringargs[])throwsException
{
System.out.println(InetAddress.getLocalHost());
}
}
Output:
l72.l6.58.3