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
Wednesday, 31 October 2018
Wikipedia project
Group
0
MAKERERE UNIVERSITY
COLLEGE OF ENGINEERING DESIGN ART AND TECHNOLOGY
DEPARTMENTOF ELECTRICAL AND COMPUTER ENGINEERING
INTRODUCTION TO ELECTRICAL ENGINEERING
COURSE CODE: ELE1112
TOPIC: LIVELIHOOD DERVISIFICATION
SUBTOPIC: Proposing new ways to break dependence on one source of livelihood
WIKIPEDIA GROUP MEMBERS
MIREMBE BETTY 17/U/ 18521/PS
MUGAMBWA PADDY 17/U/6259/PSA
SIKOOTI PONEPONE 17/U/10035/PSA
MURAMUZI ADAM 17/U/6587/PS
AHUMUZA BRIAN 17/U/2223/PS
LECTURER: Eng. Dr. Okello Dorothy
Asst. Lecturer: Mr. Budigiri Gerald
Wikipedia project
Group
1
Table of Contents
ACKNOWLEDGEMENTS ................................................................................................................................. 2
FOREWORD AND PREFACE............................................................................................................................ 2
WORK PLAN FOR THE WIKIPEDIA GROUP MEMBERS ................................................................................... 2
Code of conduct .............................................................................................................................2
Statistics of livelihood in Mbarara district .................................................................................................... 3
Biogas plant digester ..................................................................................................................................... 3
Introduction ...................................................................................................................................3
Branches of electrical engineering involved in the project .......................................................................... 3
Power: ...........................................................................................................................................3
Project description ........................................................................................................................................ 4
Benefits of the project .................................................................................................................................. 4
Key beneficiaries ........................................................................................................................................... 4
FLOW HIVE .................................................................................................................................................... 5
How it works ................................................................................................................................................. 5
Advantages .................................................................................................................................................... 6
CHALLENGES DURING THE PROJECTS. .......................................................................................................... 6
CONTRIBUTIONS OF EACH MEMBER. ........................................................................................................... 6
References .................................................................................................................................................... 7
Wikipedia project
Group
2
ACKNOWLEDGEMENTS
The Wikipedia group would like to thank its members for their tireless efforts contributed
towards this special output. It is also appreciative to its members for their precious time,
financial support, research and coordination towards this achievement.
Special gratitude goes to our introduction to electrical engineering lecturers Dr. Dorothy Okello
and Mr. Budigiri Gerald for parental mentoring and the academic advice provided to us. We
cannot take for granted the divine knowledge provided by the Almighty God and also applaud
Him for life given to us.
The group management would like to acknowledge all stake holders who were consulted and
interviewed during research and all ho discussed the draft of the projects layout. You efforts
were invaluable.
FOREWORD AND PREFACE
One of the concerns of the local farmers in villages of Mbarara district, Rubaya sub-county prior
to the eradicating poverty and achieving vision 2040 is lack of detailed information about cheap
means of making money and breaking dependence on only subsistence farming. In order to
address this common cause, our group ‘Wikipedia group’ mandates to prepare and implement the
two projects ‘biogas and flow hive projects’.
This simple handbook has been prepared for use of farmers, local Ugandans, for a
comprehensive coverage of advantages, mode of action, and goals for a particular project. The
literate, illiterate, local farmers and educationists should find this booklet useful. It has presented
in the most user friendly English with a few physics terminologies.
It is our sincere hope that this project booklet will meet will meet peoples’ needs in fulfillment to
prosperity goal and vision 2040.
WORK PLAN FOR THE WIKIPEDIA GROUP MEMBERS
DATE ACITIVITY
27th September Created the group
4th October Choose the topic
6th October Allocation of sections to handle to member
7th – 15th October Research and field study
18th October Feedback from members
26th October Compiling of ideas
1st – 4th November Writing the report
Code of conduct
All members must be present at every meeting being held unless otherwise,
All ideas are welcomed so don’t hold back any idea,
Wikipedia project
Group
3
Every member is supposed to carry out enough research about the assigned section and group
meetings were held twice a week.
Statistics of livelihood in Mbarara district
The majority of households (69 percent) derived their livelihood from subsistence farming. Only
27% of the households depended on earned income. In Mbarara district 52% of the households
use the Tadooba as the source of light, On the other hand, wood fuel was the most common fuel
used for cooking. [1i]
The people in, Mbarara district illiteracy prevents them from getting blue and white color jobs
which require qualifications. Hence end up stack in agriculture as the only source of income. [2]
Biogas plant digester
Introduction
Most people in Mbarara district are highly dependent on subsistence farming, livestock
production hence making them prone to climate changes. Following this we proposed biogas
production as one of the way of breaking dependence on one source of livelihood since it has
large animal farms that generate a substantial amount of manure, this makes the district the best
site for the production of biogas.
Biogas refers to a mixture of different gases produced by breakdown of organic matter in the
absence of oxygen.it is produced from raw materials such as green waste, municipal waste,
agriculture waste among others,
Branches of electrical engineering involved in the project
Power: This is a branch of engineering that deals with creation, storage and distribution of
electricity for industrial, commercial, residential and municipal use.
This can be applied in conversion of biogas to electrical energy by a biogas electric generator
Currently renewable energy accounts for one fifth of the overall energy consumption used
around the world. Forestry, crops, sewage, industrial residue, animal waste, and municipal waste
are all used to create the biogas renewable energy. Traditionally biogas was used for cooking and
heating purposes but these days it is being used for a number of other things as well. By the year
2050 it is thought that biogas will account for around one third of all energy.
Deforestation is the result of trees being cut down and used as fuel for fires in areas where there
is no access to electricity. With biogas, the waste that would be there anyway can be used to
create fuel. This means that trees do not have to be cut down and plants do not have to be
damaged. [3]
Wikipedia project
Group
4
Project description
Organic materials and wastes are placed in the digester (large tank), and the bacteria in the
digester breaks them down to methane through a process of anaerobic digestion. Each day the
operator of the biogas system feeds the digester with household wastes. The methane gas
produced is passed through a combustion engine to run the turbines to produce power in an
electric generator. The design of the generator is the same as an electric motor. The biogas is
then collected off from the gas outlet pipe and used for cooking lighting and other energy needs.
The wastes which are not full digested are collect from the system and used as fertilizer.
Benefits of the project
It is a way of getting rid of wastes which would be rather costly and environmental hazards.
By putting a digester into your waste treatment chain, the farmers earn income. Much as
manure is not considered to be a waste but fertilizer, if processed to produce biogas farmers earn
income and also reduce odors on theirs farms.
When waste is fed into the digester to produce biogas, the output waste can be used as liquid
fertilizer.
Improvement of health arising from avoidance of smoke, quality fertilizer and time saving
among others. [4]
Key beneficiaries
Farmer with crops now can earn an extra income from selling the remains from their gardens
after harvesting their crops; even after a bad harvest a farmers can still sell the remains to the bio
gas manufacturers in their village and still get income to sustain their lives.
Also farmers with animals earn after selling their animals manure to the bio gas manufacturers,
this diversifies their income sources not only in animals but also in selling there byproduct’s or
animals remains after collecting them from the animal farms.
Wikipedia project
Group
5
Since biogas production does not require high educated people, the people in Mbarara will be
able to be employed to work in the biogas plant, reducing on the unemployment in the district,
Not only will the people learn skills on biogas production process but also will learn how to
market and get customers to buy the biogas and consume it, enabling them to earn extra income
and be able to start up there plants with time.
With the production of electricity from the plants, people of the village can acquire affordable
power, enabling them to use electricity powered devices, like mobile phones enabling them to
stay connected to the market places.
FLOW HIVE
Is a new design of a bee hive which enables farmers to harvest honey when its ready without
dismantling the hive, the honey is pure doesn't need any processing.
In Uganda we use the tradition method of bee keeping. This requires the keeper to monitor the
hives, checking the conditions and see whether the honey is ready. All this keeps the keeper busy
and not allowing him time to attend to his other businesses or get involved in any.[5]
How it works
the hive is designed with double walled plastic frames on which the bees build the wax and fill
the with honey, it consists of a tap, presto, which is turned and the honey flows through the walls
and drains through the collect down, which lead the honey to the outlet at the bottom then its
gathered off by the bee keeper.
The bee smart is a high tech monitoring platform placed along the walls of the hive to be
analyzed. It is equipped with sensors that monitor the sounds, vibrations and heat of the hive plus
the weight of the honey.
The bee smart is connect to a mobile app that receives all the information from the device and
informs the farmers when the honey is ready to harvest in case of any abnormalities,
Wikipedia project
Group
6
[6]
Advantages
The farmers gets lots of time to create other sources of income without worrying of his bees.
The hive increasing the times the keepers harvest the honey. This because the combs are already
designed for the bee.
It reduces risks of bee stinging.
CHALLENGES DURING THE PROJECTS.
We had challenges acquiring statistics as the one UNBS has were for 2014 which are outdated.
Lack of knowledge on writing reports delayed us as we had to go and study how to write one.
Failure to meet some of the scheduled meeting, due to university programs like tests and
assignments.
CONTRIBUTIONS OF EACH MEMBER.
MIREMBE BETTY; I chaired the group meetings where each member was allocated a section
to handle. Furthermore, I also researched about the benefits and challenges of the biogas project.
Following the project, I learnt how to work in teams.
SIKOOTI PONEPONE; I was the group secretary and therefore compiled all the group
members’ findings. I also researched about the operation of the flow hive and its major
beneficiaries. I acquired research skills and how to work as a group. Knowledge about bees.
MURAMUZI ADAM; I researched about the about the advantages of the flow hive and also
compiled the acknowledgement, preface and foreword. This project has improved my interpersonal
skills and co-operation with group mates; it has enhanced my research skills.
AHUMUZA BRIAN; I analyzed the different branches of engineering to apply during our
project and the key beneficiaries of the bio gas plant digester project. Hence forth, the project
enabled me learn that engineering is applicable in the real world; thus, can be used to solve day
to day problems in a scientific way.
Wikipedia project
Group
7
MUGAMBWA PADDY; I researched about the operation of the biogas plant digester and also
looked out for the cheapest and highly profitable ways of using it. The project has broadened my
knowledge on how to put renewable resources to their full use. It has also taught me on has to
build a bio gas plant and how to operate it.
References
[1] Uganda bureau of statistics 2017,characteristics of households, National
Population and Housing Census 2014 Area Specific Profiles,pg 4
[2]Uganda bureau of statistics 2017,Education and illiteracy status, National
Population and Housing Census 2014 Area Specific Profiles,pg 21
[3]Rainbows Tanks, The importance of Biogas as renewable energy
source.,Internet:http://www.rainbowtanks.co.za/importance-biogas-renewableenergy-
source/,March 17, 2016
[4]Daily monitor, helping people embrace biogas as a source of energy,
Internet:http://www.monitor.co.ug/Business/Technology/688612-2729038-
729mef/index.html, MONDAY MAY 25 2015
[5] Ben Ochan,Ugandan journalist, Bee keeping in Uganda,
Internet:http://www.new-ag.info/00-5/focuson/focuson2.html,
[6]https://www.indiegogo.com/projects/flow-hive-honey-on-tap-directly-from-yourbeehive-
| tumworobere premere |
QN. WITH
SPECIFIC REFERENCE TO REAL LIFE CONTEXT IN SECONDARY SCHOOLS IN UGANDA TODAY,
ASSESS THE ROLE OF MASS MEDIA IN THE PROCESS OF FORMAL SOCIOLISATION.
Socialisation
is the process by which a person acquires the knowledge, skills, and
depositions that make him/her more less integrated member of society that is
according to Ezewu (1983). According to Qura, socialisation is the process
across the life span through which individuals acquire and interact with values
and social standards of specific society and culture. According to my own
observation from the already given definitions, socialisation is a lifelong
process by which members of a given society take some time to learn and become
competitive members of a given society and live fully as responsible adults.
There are two types of formal socialisation that is formal socialisation
through schools in class room teaching by acquiring knowledge, values and
attitudes. On the other hand, informal socialisation gives individuals skills,
norms, values and ideas through interaction with other people. Other
instrumental agents of socialisation include family, religion, schools,
community, and peer groups. It plays a major role in identity formal formation
and social functioning of a given group people in society depending on the
preferred media. Mass media is a diversified collection of media technologies
that reach a large audience via mass communication and broadcast transmission.
Mass media is considered as a powerful agent of socialisation responsible for
shaping an individual’s socialisation process. It does not promote
socialisation process but promotes socialisation interact. It provides a wide
range of platform for people to interact and acquire social skills. The mass
media as a socialising agent includes televisions, magazines, newspapers,
radios, movies, films, internet, tapes, disks and videos. As for the case in
Uganda today, examples of mass media are NTV, New vision, NBS, Bukedde TV and
newspaper, radios like capital FM Uganda, UBC and others. The media is a
powerful agent of socialisation for teenagers around Uganda as this appeals to
teenage mind. Secondary schools in Uganda include Mbarara high school
(mbarara), Ntare school (mbarara), kampala high school, St. mary’s kitende, and
others. The media brings exposure to the students to the entire world therefore
enlightening and enlarging their socialisation aspects.
Just
as everything has got advantageous and disadvantageous roles, it is right to
assert that mass media has also got negative and positive roles to formal
socialisation of students in secondary schools however much the vital part of
it out ways the negative one.
To begin with, the mass media has enhanced the
formal socialisation through making it possible for students to do thorough
research by way of strengthening their academic part of holistic education.
Through programmes and information passed on media like televisions, printing
press like newspapers, poems, textbooks, novels, hand outs, plays and others,
students have been exposed to them. A case in point is “pass UCE” and “do it
yourself” in new vision, students are able to get questions and marked helping
them to know how far they have gone. Further more, most of the schools
especially first and second world schools in Uganda have got libraries embedded
with different forms of literature like poems, novels like oliver twist, heart
of the matter, plays like Romeo and Juliet which help students to adjust
accordingly and know how to deal and socialise with every society. Not only
that, academic debates have been carried out on televisions like NTV, urban TV,
and NBS television every Sunday at 3pm. This develops their confidence as in
socialising with each other and gives them other topics to discuss about and
interact with each other. Through the above, mass media plays an effective role
to the formal socialisation of the students as they interact with one another
and share what they discovered from different aspects of mass media.
The mass media also plays a big role in promoting
awareness and doing the informative role to the students. They are exposed to
the world and this helps them to know information dissemination, the ever
airing, circulating and propagating news can reach the students through the
mass media. This keeps them updated about what is happening in the world and
there country Uganda in particular. As for the case in Uganda, students get
information from TVs, newspapers, magazines, and social media like facebook
about what is happening the country such political sagas like togikwako in the parliament, Rwenzururu
secessionist attempt, natural calamities like Bududa land slides. In addition,
they are exposed to the current situation of a corruptible country Uganda and
how they can best live in it. More still, they are exposed to the best
universities to join after their high school level which gives them a big zeal
for them to work hard. In agreement to this, through the media like TVs,
radios, and newspapers , students are able to know how schools have performed
after the release of UCE and UACE exams by UNEB. Basing on this point, it
should be noted that the media through informing the students about all
disastrous and catastrophic aspects in the country, they are able to learn
norms and values which promote behaviours hence bringing advancement in the
interaction and socialisation with each other.
Mass media has done a great job to secondary school
students by providing interaction and entertainment to them. Through internet
like facebook, whatsapp, they are able to interact with each other for
different views. Through these interactions, they copy each others actions and
behaviours that finally leads to adjustment in their attitudes. More further,
through advertisements, mass media provides a platform and a stepping stone for
students to begin formal educative discussion groups from different schools, hold
debates, participate and compete in music dance and drama, games and sports
like soccer galas which happen annually up to national level. Through these
activities, friendship is promoted through interactions and socialising with
different schools. Therefore it is right to note that formal socialisation is
promoted via the mass media.
Mass media has also been responsible and has
spearheaded the provision of sex education to the students in secondary schools
in Uganda today. Through magazines newspapers and other sex programs, students
are able to know their roles according to sex, they learn how to interact with
people of the opposite sex and live in harmony with others, skills are also
imported on them on how to look and care about themselves and how to avoid
sexual immorality and all its negative consequences. This education makes
students interact with one another hence promoting formal socialisation.
However much the mass media has turned to be a learning
aid for secondary school students in Uganda today, It has also got negative
effects towards their formal socialisation though to a lesser extent.
Mass media has promoted immorality like sexual immorality,
nudity, violence permissiveness, alcoholism among others in secondary students in Uganda, students end up
getting adopted to newspapers like red paper, onion, senga programs in Bukedde
and shwenkazi in Orumuri. They are also exposed to pornographic literature like
blue movies romantic love stories like titanic, Romeo and Juliet, its love, who
loves me among others. Sexual immorality like prostitution, fornication, homosexuality
and lesbianism as the case in most Ugandan simple schools which result from the
pornographic literature they are exposed to. Furthermore they watch videos, films
and fiction which show use of physical force, great fighters, warriors, among
others. These students end up developing high levels of violent acts like
fighting and aggressiveness and disobedience to the law at its apex while socialising
with others. Therefore with the above, mass media turn out to be immorality
instructor than giving effective information to the students thus limiting
formal socialisation.
To sum it all in my conclusion, mass media has done
a great positive role in secondary schools as far as formal socialisation is
concerned by strengthening and tightening their relations and interactions with
other students, creates awareness and entertainment as well thus promoting the
process of formal socialisation, however to a lesser extent it has also brought
about negative consequences like sexual immorality violence, nudity,
disobedience to the law among others hence limiting the process of formal socialisation
in the secondary schools of Uganda today.
1.
Ezewu, E (1986) Sociology of education,
Longman, London and Lagos
2.
https//:www.quora.com
3.
J. Matovu article 1990
4.
Musgrave, P.W 1976 Sociology of
education, London and New-york
5.
New vision, do it yourself and pass UCE
Friday, 19 October 2018
story by Tumworobere premier
QN. “FUTURE MEN AND WOMEN ARE DESTINED TO PERFORM
DIFFERENT ROLES IN SOCIETY AND IT IS SIMPLY INEFFICIENT TO TRAIN THEM IN THE
SAME WAY” WITH REFERENCE TO CURRICULUM
DIMENSIONS, DISCUSS HOW A COUNTRY CAN ESTABLISH A HOLISTIC EDUCATION SYSTEM FOR
ITS CITIZENS.
Future
men and women are simply all the children, youth, students, learners ranging
from nursery, primary secondary and all other institutions of higher learning.
All these have different abilities, capacities and strengths therefore they are
entitled to perform different activities in the society. Some have talents in
football, construction, cooking, dancing, carpentry, mechanics and academically
talented ones. It would be automatically unfair to train them in the same way,
one class, one content, and one situation yet they are gifted differently. For example a student starts to fail mathematics from
primary, finds its compulsory at O’level and made to pursue subsidiary
mathematics at A’level which doesn’t make any sense as far giving holistic
education is concerned. The government of a country like Uganda should arrange
different strategies and put across all the required necessities in order to
provide holistic education that would favour all students in their respective
capacities and abilities, produce skilled citizens that are going to cause
change in the society.
There
is no standard definition of curriculum since all the educationists have
varying views. Curriculum is a greek word which is embedded with different
meanings from different scholars and philosophers . some take it as syllabus,
notes, textbooks, teaching aids, among others. Its therefore from this point
that different scholars have given their views on the meaning of curriculum
basing on the fact that no single definition can define it. Bishop (1985)
defines curriculum as the total sum of all experiences a pupil undergoes, Kerr
(1965) defines it as all learning which planned and guided by the school
whether it is carried out in groups or individually inside or outside the school,
Farrnt(1964) defines it as all that is taught in school including subjects and
all those aspects of life the exercise and influence the life of the children,
Bobbit (1918) in Okello V and Ocheng M.K(1996) defines curriculum as those
things which children and youth must do and experience by way of developing
ability to do things well that make up affairs of adult life. Finally Stehouse
(1975) defines curriculum as the total effort of the school to bring about
desired outcomes in school and outside school situations. However according g
to all definitions given by all different scholars, I therefore view curriculum
as the skills and experiences the child must undertake than only receiving
knowledge and content given by the teacher in classroom.
From
the above definitions of curriculum, we obtain curriculum dimensions as viewpoints
of curriculum, they include formal, non-formal, informal, and guidance and
counselling as the major dimensions. Formal curriculum includes formal
activities undertaken in class or outside for which the timetable of the school
allocates specific periods of teaching time. This dimension is documented in
scope and sequence for example lessons. Non-formal curriculum comprises of all
those planned experiences outside the formal curriculum for example sports,
clubs, drama, debates etc. it is voluntary in nature and favours learners
interests and preferences. According to Urevbu(1990), informal curriculum is not
formalised in that they are those things learners learn at school because of the
way in which work of the school is planned and organised for example school life
teaches obedience to authority, punctuality, neatness, techniques for passing
exams and leadership roles. Guidance and counselling is process by which
learners are helped to understand, and use aptitude abilities and interests,
they are given career guidance and advice on how to make choices.
Education
according to Farrnt (1964), defines it as a universal practice engaged in by
societies at all stages of development leading to new knowledge and experience
hence growth. However Sirous Mahmoud in his article defines education as encompassing views of reality education
experiences that promote a more balance development of cultivate relationships
among different aspects of an individual.
Holistic
education refers to a philosophy of education based on the premise that person
finds identity, meaning and purpose in life through connections to the
community and the entire world. It can also be defined as functional education
relation between parts and the whole. However according to my own view,
holistic education is defined as education that favours all kinds of students
with different talents, abilities, strengths and capacities to live independent
adult lives. This is got through imparting skills at all stages that can help
them change the societies they live in. the actual determinants of holistic
education can be teachers available since they perform a big role in designing
the curriculum and imparting skills to learners, resources available, culture
and need. According to Tylor 1949, alleges that need is used in psychological writings
of Prescott and others. They view a human being as dynamic organism and to keep
it in equilibrium, its necessary that needs be met. In this sense, every
organism is continually meeting its needs that is reacting in such a way as to
relieve these forces that bring about imbalance.
Therefore
for a country like Uganda to establish a holistic education for its citizens,
must design and draw the curriculum which balances all four dimensions and
should be carefully implemented than not following the kind of behaviour
expected and the content the behaviour applies. However the new curriculum
cannot be implemented until necessary teaching materials like textbooks,
workbooks and any other visual audio materials that are essential to the course
that have been produced and distributed to schools and teachers and teachers
have been trained in their use consequently. Introducing new curriculum is a complex task according to Farrnt 1964.
Therefore the following reforms must be put into consideration while designing
the curriculum for Uganda to establish holistic education.
To
begin with, the government should do emphasise vocationalisation of skills that
aim at producing job creators than job seekers per the case in Uganda today.
the government can do this by setting up technical institutions for tailoring,
agriculture, catering, brick making, mechanics, carpentry, weaving where
learners of different skills can take part. Further more according to
Bobbit (1918) emphasised the development
of skills whereby he encourages ‘development of ability to do things well that
make up the affairs of adult life’ He adds that learners should not be taught
what they will never use in life because that would be a waste or spoilt
education. So in order to reduce waste, educators had to institute a process of
scientific measurement leading to predictions as ones future goals in life. He
therefore emphasised and advocated for education according to need and
predicted social and vocational roles. In my own view, I agree with Bobbit in
that they are those skills that can give education for life. A student can use
them to provide sustainability and cause change in the society than formal
curriculum. Though this may be of great impact to the education system of
Uganda, resources, teachers, and institutions may not be available to provide
holistic education.
Secondly,
the government/ country should put emphasis on practical teaching that can
promote holistic education for example apart from first world schools, many of
the schools don’t have enough resources like laboratories in case of science
subjects( biology, physics, chemistry, principles of agriculture etc),
libraries for research, trained teachers to impact students with skills.
According to bishop (1985) encourages more science in schools in order to
produce better qualified candidates for higher level technical and scientific
studies. He goes ahead to emphasise that resources would promote the prosper of
science in schools even starting from primary level. He alleges “many schools
have a prejudice against teaching practical subjects since the theorist has
more snob prestige than the practitioner, schools tend to be snobbish against
their pupils( dirtying their hands). In the lower classes of primary school,
work experience may take the form simple handwork with the objective being to
train them use their own hands”. I support bishop in that it may take a form of
learning a craft which develops technical thinking and creative capacities. Therefore
at this stage some work experience can be produce in real life. In addition to
the above, the star magazine Mengo senior school emphasises and practices the
teaching of practical subjects like woodwork and tailoring. “ Mengo is unique
in that it is concentrating on education and training that builds fundamental
traits, we believe that a person who is morally educated will be a lot better
equipped to move in life and succeed. However much this would be of great
importance on Ugandan education system, it may be hindered and ineffective
since the resources are scarce and almost a large percentage of schools cannot
afford it.
Thirdly,
the government should check and adjust its curriculum that is based on culture.
Learners should be taught in their own language to promote holistic education.
This would help to teach students their traditions, norms, beliefs and customs.
Further more, not only that, Uganda’s education is more based on western
culture that is students are taught in English language. Therefore as the mode
of communication can also play a big role in promoting holistic education since
students are well conversant with the content taught in their language. However
much this may be possible, Uganda has limited resources like teachers and
textbooks for teaching native languages. Uganda is a multi-linguistic country
Much
emphasis should also be put on the promotion of talent and ability of a
student. Students or learners with abilities and talents like rugby, football,
netball, tennis, athletics, actors and actresses should be helped to develop
their talents. This must be favoured all along from childhood whereby they be
helped to develop their talents and earn a living for example Denis Onyango of
Uganda cranes, and Bobi wine (the singer turned politician) who are popular and
have caused change in the societies they live in. according to Herbert, in
Tanner D and Tanner L (1995) stresses that the teacher must present new ideas
in a way that associates them with ideas that are already part of the students
experience. This meant that a teacher had to know of the child’s previous
knowledge and interest. In my abide with
the above scholar, teachers are entitled to renovate their learners and
motivate them to use their talents that would turn them into skilled
individuals hence providing holistic education. To top on that, in the Monday
January 25th 2010 new vision, the DEO of Wakiso district blamed some
teachers who put much emphasis on examinations at the expense of talent
developing. In line with the DEO, Mathias Mazinga in new vision 28th
February 2017 supports development of firm structures to develop talents in
sports. “sports is now a history to most students today, what matters most is
passing with good grades” therefore if the government would be in position of
implementing sports and other talents through offering scholarships/ bursaries
to encourage students develop their talents in addition to constructing complex
sports arenas at least this would be a step forward to holistic education.
Lastly,
the government/country should emphasise child centred system of education. This
is where children take command of their own learning. Teachers are there to
provide support and facilitate the child’s learning but children determine the
direction of their own following their capabilities, interests, and desires for
example when one wants to be a footballer or musician. Kelly (1989) also
supports tanner D and tanner l by saying that teachers need to be sensitised
and helped to recognise and identify the hidden implications of some of the
materials and experiences they offer to their pupils. This can be done by
encouraging them to specialise earlier enough in subjects of their own
interests and desires by providing necessary materials required. Tyler (1949)
agrees with Kelly and emphasises the theory of progressive education where learners
interests must be identified so as to serve a purpose on educational intention.
This specialisation would lead to holistic education in that a child who would
have started practising music dance and drama, by the time he becomes an adult
would be very well talented and can sustain him or herself hence holistic
education. However this would be made in a country like Uganda where students
are taught from similar classes from nursery to secondary yet they gifted
differently.
To
sum it all, holistic education would be established in a country like Uganda if
all the four dimensions would be put into practice and, actual determinants of
holistic education would be put into consideration like resources and teachers.
Therefore if the curriculum of Uganda in particular would be adjusted according
to culture, following learners interests, putting emphasis on talents, among
others. If all this is done, holistic education will be established.
REFERENCES ( TEXT BOOKS)
1. Bishop.G
(1985) Curriculum development, macmillan education ltd, London P 1-3, 16-22
2.
Bobbit 1918 curriculum development,
longman, London, P 1,3 and 7
3.
Farrant. J.S (1964) principles and
practices of education, longman, UK P 18-24
4.
Kelly. A.V (1989) The curriculum theory
and practice, chapman publishing limited, london P 12-13
5.
Kelly. A.V (1977) The curriculum theory
and practice, sage publications, London P 10
6.
Okello. V and Ochieng M.K 1996
curriculum studies, Makerere university, Kampala, P 3
7.
Tanner D and Tanner L 1995 curriculum development
theory into practice, Merill, an imprint of prentice Hall Columbus ohio opio
8. Tyler.
R.W 1949 Basic principles of curriculum and instructions, the university of
Chicago press, London P 5-7
OTHER SOURCES
1. Emmanuel
Byamugisha, DEO wakiso blames some teachers, New vision Monday January 25th
2010
2.
https://en.m.wikipedia.org.>wiki>holisticeducation
3.
Mazinga Mathias, the gov’t must build
firm structures to develop sports, New vision 28th February 2017
4. Stephen
Sima, schools focus on tests is damaging education, New vision Tuesday march 20th
2018
The star magazine
Mengo senior school , kampala , relevancy of school subjects to the community
outside school P 42,57,5
THESE BY MURAMUZI ADAM
MUGUME
@BROOKS_ADAMZ
0784503974/0750445414
One thing I have learned in a long life: that all our science, measured
against
reality, is primitive and childlike—and yet is the most precious thing
we have. —ALBERT EINSTEIN
Education makes a people easy to lead, but difficult to drive; easy to
govern but impossible to enslave —HENRY P. BROUGHAM
No man really becomes a fool until he stops asking questions.—CHARLES P.
STEINMETZ
Take risks: if you win, you will be happy; if you lose you will be wise.—PETER
KREEFT
The 12 Principles of character: (1) Honesty, (2) Understanding, (3)
Compassion,
(4) Appreciation, (5) Patience, (6) Discipline, (7) Fortitude, (8)
Perseverance,
(9) Humour, (10) Humility, (11) Generosity, (12) Respect.—KATHRYN B. JOHNSON
Our schools had better get on with what is their overwhelmingly most
important
task: teaching their charges to express themselves clearly and with
precision in
both speech and writing; in other words, leading them toward mastery of
their
own language. Failing that, all their instruction in mathematics and
science is a
waste of time.—JOSEPH WEIZENBAUM, M.I.T.
No honest man can be all things to all people.—ABRAHAM LINCOLN
Do all the good you can, By all the means you can, In all the ways you
can, In all the places you can, At all the times you can, To all the people you
can, As long as ever you can.—JOHN WESLEY
Do you want to be a hero? Don't be the kind of person who watches others
do
great things or doesn't know what's happening. Go out and make things
happen.
The people who get things done have a burning desire to make things
happen, get
ahead, serve more people, become the best they can possibly be, and help
improve the world around them.—GLENN VAN EKEREN
How far you go in life depends on your being tender with the young,
compassionate
with the aged, sympathetic with the striving, and tolerant of the weak
and
the strong. Because someday in life you will have been all of these.—GEORGE
W. CARVER
There is a story about four men named Everybody, Somebody, Anybody, and
Nobody. There was an important job to be done, and Everybody was asked
to do
it. Everybody was sure that Somebody would do it. Anybody could have
done it,
but Nobody did it. Somebody got angry about that, because it was
Everybody's
job. Everybody thought that Anybody could do it, and Nobody realized
that
Everybody wouldn't do it. It ended up that Everybody blamed Somebody,
when
actually Nobody did what Anybody could have done.—ANONYMOUS
If a man writes a better book, preaches a better sermon, or makes a
better mousetrap
than his neighbor, the world will make a beaten path to his door.—RALPH
WALDO EMERSON
The Ten Commandments of Success
1. Hard Work: Hard work is the best investment a man can make.
2. Study Hard: Knowledge enables a man to work more intelligently and
effectively.
3. Have Initiative: Ruts often deepen into graves.
4. Love Your Work: Then you will find pleasure in mastering it.
5. Be Exact: Slipshod methods bring slipshod results.
6. Have the Spirit of Conquest: Thus you can successfully battle and
overcome
difficulties.
7. Cultivate Personality: Personality is to a man what perfume is to the
flower.
8. Help and Share with Others: The real test of business greatness lies
in giving
opportunity to others.
9. Be Democratic: Unless you feel right toward your fellow men, you can
never
be a successful leader of men.
10. In all Things Do Your Best: The man who has done his best has done
everything.
The man who has done less than his best has done nothing.—CHARLES M. SCHWAB
The future has several names. For the weak, it is the impossible. For
the faith hearted,
it is the unknown. For the thoughtful and valiant, it is ideal.—VICTOR
HUGO
The recipe for ignorance is: be satisfied with your opinions and content
with your
knowledge.—ELBERT HUBBARD
Saturday, 11 November 2017
MAKERERE UNIVERSITY LIFE
THESIS QUESTION: Is
getting involved in social life good or bad for a Makerere university students?
Imagine
one graduates but is unable to get a job because he/she did nothing socially at
Makerere university but focused on studying, doing assignments, course works
and discussions. Because of this he/she did not develop a social network or
social skills. To my own understanding, not only are sororities, fraternities,
and other social organizations like Makerere Engineering Society, Makerere Law
Society good for students, they actually play an important role in teaching
students how to be ready for life after university. I truly emphasize the point
that it is all about books, one needs to upright wholesomely that is socially,
academically, and morally. These social organizations are important because
they help university students to develop social skills, gain friendship
networks that can help them later in life and learn how to balance work and
fun.
Makerere
organizations are not just for fun because developing skills here at campus is
an important part of becoming a good engineer of your discipline and keeping a
job. The heavy change in Uganda’s employment trends have also encroached on
interview questions. Many companies need a well accomplished employee excellent
at all sectors of life. A key example is when my sister was asked to present a
certificate as evidence to have held a leadership position while at Makerere
university. Success after campus happens not just because people study hard,
but also because they develop a network of contacts via WhatsApp, Facebook, and
other social platforms. The main events like university ‘bazaar’, and fresher’s
ball, plus soccer gala help students develop coordination and developing a
strong solidarity. Connections are started right from campus for example from
halls of residence like Lumumbox for Lumumba and Marystuart, Mitchelex for Mitchel
and complex halls, and Afristone for Africa and Livingstone halls of Makerere.
Solidarity is also manifested in the recent ‘kogikwatako’
strike against the amendment of the article 102(b) of the constitution. This
not only helps students to secure jobs after study but also getting places for
industrial training to get interpersonal skills.
Small
responsibilities held while at campus in university groups for example group
leaders help in preparing students for a life time of balancing their needs for
example work and family, and friends. They learn how to work hard on their jobs
while finding time for family, friends and other hobbies. Please note that
one’s CV must account for hobbies and interests which are developed while at
campus.
To
my own personal point of view, I have learnt a lot from Makerere university
because I have met new friends, new experience and completely new life which I
need in the near future. I strongly implore my fellow gallant intellectuals of
the ivory tower to be part of social organizations. The audience of parents
should understand that their adult children deserve to be part of life outside
books. Makerereans should develop relationships as well as academic knowledge
at the back of minds.
‘ITS NOT ALL ABOUT BOOKS’
Subscribe to:
Comments (Atom)


