0% found this document useful (0 votes)
19 views28 pages

Java Printout New

Java is a high-level, object-oriented programming language developed by Sun Microsystems, known for its platform independence and security features. The document provides a comprehensive overview of Java's syntax, data types, operators, and programming concepts, including identifiers, modifiers, and arrays. Additionally, it includes examples of basic Java programs and highlights the importance of Java's runtime environment and its capabilities for developing robust applications.

Uploaded by

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

Java Printout New

Java is a high-level, object-oriented programming language developed by Sun Microsystems, known for its platform independence and security features. The document provides a comprehensive overview of Java's syntax, data types, operators, and programming concepts, including identifiers, modifiers, and arrays. Additionally, it includes examples of basic Java programs and highlights the importance of Java's runtime environment and its capabilities for developing robust applications.

Uploaded by

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

JAVA is a high-level programming language originally developed by Sun Microsystems and

released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX. This tutorial gives a complete understanding of Java. Java is guaranteed to be
Write Once, Run Anywhere.

Java is:

i. Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
ii. Platform independent: Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by virtual
Machine (JVM) on whichever platform it is being run.
iii. Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java
would be easy to master.
iv. Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
v. Architectural-neutral: Java compiler generates an architecture-neutral object file format
which makes the compiled code to be executable on many processors, with the presence of
Java runtime system.
vi. Portable: Being architectural-neutral and having no implementation dependent aspects of the
specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary which is a POSIX subset.
vii. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
viii. Multithreaded: With Java's multithreaded feature it is possible to write programs that can do
many tasks simultaneously. This design feature allows developers to construct smoothly
running interactive applications.
ix. Interpreted: Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is
an incremental and light weight process.
x. High Performance: With the use of Just-In-Time compilers, Java enables high performance.
xi. Distributed: Java is designed for the distributed environment of the internet.

1
xii. Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.

Java - Environment Setup


Java SE is freely available from the link Download Java. So you download a version based on your
operating system. You can refer to installation guide for a complete detail.

Java Basic Syntax:


 Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as
well as behaviors -wagging, barking, eating. An object is an instance of a class.
 Class - A class can be defined as a template/ blue print that describe the behaviors/states that
object of its type support.
 Methods - A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
 Instant Variables - Each object has its unique set of instant variables. An object's state is
created by the values assigned to these instant variables.

First Java Program:


Let us look at a simple code that would print the words Hello World.

public class MyFirstJavaProgram {


public static void main(String []args){
System .out.println("Hello World");
}
}

About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have
different meaning in Java.
 Class Names - For all class names the first letter should be in Upper Case. If several words
are used to form a name of the class each inner words first letter should be in Upper Case.
Example: class MyFirstJavaClass
 Method Names - All method names should start with a Lower Case letter. If several words
are used to form the name of the method, then each inner word's first letter should be in
Upper Case. Example: public void myMethodName
2
 Program File Name - Name of the program file should exactly match the class name. When
saving the file you should save it using the class name Rememberjavaiscasesensitive and
append '.java' to the end of the name.
ifthefilenameandtheclassnamedonotmatchyourprogramwillnotcompile.
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as'MyFirstJavaProgram.java'
 public static void main(Stringargs[]) - java program processing starts from the main
method which is a mandatory part of every java program…

Java Identifiers:
All Java components require names. Names used for classes, variables and methods are called
identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 After the first character identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value
 Examples of illegal identifiers: 123abc, -salary

Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are
two categories of modifiers:
 Access Modifiers: default, private, public, protected:
Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:
o Visible to the package – the default. No modifiers are needed.
o Visible to the class only – private.
o Visible to the world – public.
o Visible to the package and all subclasses – protected.

 Non-access Modifiers: static, final, abstract, strictfp


Java provides a number of non-access modifiers to achieve many other functionality.
o The static modifier for creating class methods and variables

3
o The final modifier for finalizing the implementations of classes, methods, and
variables.
o The abstract modifier for creating abstract classes and methods.
o The synchronized and volatile modifiers, which are used for threads.

Java Variables:
We would see following type of variables in Java:
 Local Variables
 Class Variables (Static Variables)
 Instance Variables (Non-static variables)

Java Arrays:
Arrays are objects that store multiple variables of the same type. However, an array itself is an
object on the heap. We will look into how to declare, construct and initialize in the upcoming
chapters.

Java Keywords:
The following list shows the reserved words in Java. These reserved words may not be used as
constant or variable or any other identifier names.

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long native new package

private protected public return

4
short static strictfp super

switch synchronized this throw

throws transient try void

volatile while

Comments in Java:
Java supports single-line and multi-line comments very similar to c and c++. All characters available
inside any comment are ignored by Java compiler.

public class MyFirstJavaProgram {


/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public static void main(String []args){
// This is an example of single line comment
/* This is also an example of single line comment. * /
System .out.println("Hello World");
} //End main method
} //End class MyFirstJavaProgram

Data Types in Java:


There are two data types available in Java:
 Primitive Data Types
 Reference/Object Data Types

Primitive Data Types:


There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Let us now look into detail about the eight primitive data types.
i. Byte: 8-bit signed two's complement integer; Min value is -128 (-2^7) & Max value is
127 (inclusive)(2^7 -1). Example: byte a = 100 , byte b = -50

5
ii. Short: 16-bit signed two's complement integer; Min value is -32,768 (-2^15) & Max
value is 32,767 (inclusive)(2^15 -1). Example: short s = 10000, short r = -20000
iii. Int: 32-bit signed two's complement integer; Min value is -2,147,483,648 (-2^31) & Max
value is 2,147,483,647 (inclusive)(2^31 -1). Example: int a = 100000, int b = -200000
iv. Long: 64-bit signed two's complement integer; Min value is (-2^63) & Max value is
(2^63 -1)(inclusive). Example: long a = 100000L, long b = -200000L
v. Float: Single-precision 32-bit IEEE 754 floating point. Float data type is never used for
precise values such as currency. Example: float f1 = 234.5f
vi. Double: Double-precision 64-bit IEEE 754 floating point. Double data type should never
be used for precise values such as currency. Example: double d1 = 123.4
vii. Boolean: Boolean data type represents one bit of information. There are only two
possible values: true and false. Default value is false. Example: boolean one = true
viii. Char: Single 16-bit Unicode character. Min value is '\u0000' (or 0) & Max value is '\uffff'
(or 65,535 inclusive). Char data type is used to store any character. Example: char letterA
='A'

Reference Data Types:


 Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.
For example: Employee, Puppy etc.
 Class objects, and various type of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any compatible
type.
 Example: Animal animal = new Animal("giraffe");

Java Literals:
A literal is a source code representation of a fixed value. They are represented directly in the code
without any computation.
Literals can be assigned to any primitive type variable. For example:
byte a = 68;
char a = 'A'
String literals in Java are specified like they are in most other languages by enclosing a sequence of
characters between a pair of double quotes. Examples of string literals are:
"Hello World"
6
"two\nlines"
"\"This is in quotes\""
Java language supports few special escape sequences for String and char literals as well. They are:

Notation Character represented Notation Character represented


\n Newline (0x0a) \" Double quote
\r Carriage return (0x0d) \' Single quote
\f Formfeed (0x0c) \\ backslash
\b Backspace (0x08) \ddd Octal character (ddd)
\s Space (0x20) \uxxxx Hexadecimal UNICODE character
(xxxx)
\t tab

Java Basic Operators:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:

Assume integer variable A holds 10 and variable B holds 20, then:

(1) The Arithmetic Operators:

(2) The Relational Operators:

7
(3) The Bitwise Operators:
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. Assume if a = 60; and b = 13; now
in binary format they will be as follows:

a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

(4) The Logical Operators:

8
(5) The Assignment Operators:

(6) Misc or Miscellaneous Operators:


There are few other operators supported by Java Language.

i. Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

9
Following is the example:

public class Test {


public static void main(String args[]){
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This would produce the following result −

Value of b is : 30
Value of b is : 20

ii. instanceof Operator:


This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). instanceof operator is written as:

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true. Following is the
example:

public class Test {


public static void main(String args[]){
String name = "James";

// following will return true since name is type of String


boolean result = name instanceof String;
System.out.println( result );
}
}
10
This would produce the following result:

true

Precedence of Java Operators:

() [] . (dot operator)

Number Methods:
Here is the list of the instance methods that all the subclasses of the Number class implement:

SN Methods with Description SN Methods with Description


1 equals() 12 log()
Determines whether this number object is Returns the natural logarithm of the
equal to the argument. argument.
2 valueOf() 13 pow()
Returns an Integer object holding the value Returns the value of the first argument
of the specified primitive. raised to the power of the second
argument.
3 toString() 14 sqrt()
Returns a String object representing the Returns the square root of the argument.

11
value of specified int or Integer.
4 parseInt() 15 sin()
This method is used to get the primitive Returns the sine of the specified double
data type of a certain String. value.
5 abs() 16 cos()
Returns the absolute value of the Returns the cosine of the specified double
argument. value.
6 ceil() 17 tan()
Returns the smallest integer that is greater Returns the tangent of the specified
than or equal to the argument. Returned as double value.
a double.
7 floor() 18 asin()
Returns the largest integer that is less than Returns the arcsine of the specified double
or equal to the argument. Returned as a value.
double.
8 round() 19 acos()
Returns the closest long or int, as indicated Returns the arccosine of the specified
by the method's return type, to the double value.
argument.
9 min() 20 atan()
Returns the smaller of the two arguments. Returns the arctangent of the specified
double value.
10 max() 21 toDegrees()
Returns the larger of the two arguments. Converts the argument to degrees
11 exp() 22 toRadians()
Returns the base of the natural logarithms, Converts the argument to radians.
e, to the power of the argument.
23 random()
Returns a random number.

Character Methods:
Here is the list of the important instance methods that all the subclasses of the Character class
implement:

12
SN Methods with Description SN Methods with Description
1 isLetter() 5 isLowerCase()
Determines whether the specified char Determines whether the specified char
value is a letter. value is lowercase.
2 isDigit() 6 toUpperCase()
Determines whether the specified char Returns the uppercase form of the
value is a digit. specified char value.
3 isWhitespace() 7 toLowerCase()
Determines whether the specified char Returns the lowercase form of the
value is white space. specified char value.
4 isUpperCase() 8 toString()
Determines whether the specified char Returns a String object representing the
value is uppercase. specified character valuethat is, a one-
character string.

Java - Strings Class:


Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.

Creating Strings:
The most direct way to create a string is to write:

String greeting = "Hello world!";

String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor
method that you can use with strings is the length() method, which returns the number of characters
contained in the string object.
Below given program is an example of length() , method String class.

public class StringDemo {


public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}// end of main method
}// end of class

13
This would produce the following result:

String Length is : 17

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:

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in:

"Hello," + " world" + "!" which results in "Hello, world!"

Let us look at the following example:

public class StringDemo {


public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
This would produce the following result:

Dot saw I was Tod

Here is the list of few methods supported by String class:

char charAt(int index), String replace(char oldChar, char newChar),

String substring(int beginIndex), char[] toCharArray(),

String toLowerCase(), String toUpperCase(),

String trim(), String toString(), etc.

14
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements;
}

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax:
The syntax of a do...while loop is:
do
{
//Statements;
}while(Boolean_expression);

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements;
}

Enhanced for loop in Java:


As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:

15
public class TestArray {
for(declaration : expression) public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
{
// Print all the array elements
//Statements; for (double element: myList) {
System.out.println(element);
}
}
}}
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop
or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of
code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
break;

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;

The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:

if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

16
The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax:
The syntax of a if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.
Syntax:
The syntax of a if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the one of the above condition is true.
}

Nested if...else Statement:


It is always legal to nest if-else statements. When using if , else if , else statements there are few
points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
The syntax for a nested if...else is as follows:

17
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}

The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.
Syntax:
The syntax of enhanced for loop is:
switch(expression){
case value :
//Statements;
break; //optional
case value :
//Statements;
break; //optional

//You can have any number of case statements.

default : //Optional
//Statements;
}

The Math Class


The math class provides an extensive set of mathematical methods in the form of a static class library
for manipulating the different mathematical expressions such as e, π, sin, cos, etc. Note that the
trigonometric ratios, sin, cos and tan are implemented in radian measurement and not in
degree in Java. You need to write your own code to convert the angles given in degrees to
radians. Also note that π – rad = 1800.

Examples of methods available in the Math class are:


Math.PI, Math.E, Math.abs(), Math.cos(), Math.sin(), Math.tan(), Math.log(), Math.exp(), etc.
(See examples at the practical exercises column).

18
Java Methods:
A Java method is a collection of statements that are grouped together to perform an operation. When
you call the System.out.println method, for example, the system actually executes several statements
in order to display a message on the console.
In general, a method has the following syntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
A method definition consists of a method header and a method body. Here are all the parts of a
method:
 Modifiers: The modifier, which is optional, tells the compiler how to call the method. This
defines the access type of the method.
 Return Type: A method may return a value. The returnValueType is the data type of the
value the method returns. Some methods perform the desired operations without returning a
value. In this case, the returnValueType is the keyword void.
 Method Name: This is the actual name of the method. The method name and the parameter
list together constitute the method signature.
 Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a method. Parameters are optional;
that is, a method may contain no parameters.
 Method Body: The method body contains a collection of statements that define what the
method does.

Java Classes & Objects:


Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/ blue print that describe the behaviors/states that object
of its type support.
A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
19
A class can contain any of the following variable types:
 Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
 Instance variables: Instance variables are variables within a class but outside any method.
These variables are instantiated when the class is loaded. Instance variables can be accessed
from inside any method, constructor or blocks of that particular class.
 Class variables: Class variables are variables declared with in a class, outside any method,
with the static keyword.

Exceptions Handling:
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
}

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
}

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
20
You can throw an exception, either a newly instantiated one or an exception that you just caught, by
using the throw keyword. Try to understand the different in throws and throw keywords. throws is
used to postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

The finally Keyword


The finally keyword is used to create a block of code that follows a try block. A finally block of code
always executes, whether or not an exception has occurred. Using a finally block allows you to run
any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
21
Errors in Programming
Errors (bugs) are bound to occur and removed (debugged) in our programs. The following common
errors exist in programming:
 Syntax error: When a Programmer violates the grammatical rules of the programming
language he/she is using. E.g.: misspell a keyword, absence of semi-colon, etc.
 Semantic error: This error occurs if the compiler cannot attach meaning to a program
statement. E.g.: assigning a char value to an integer location, etc.
 Compile-time error: This occurs at compilation stage of the program development. They are
actually syntax and semantic errors.
 Logic error: This is usually made by programmers. The program will compile and run
perfectly but the output will be erroneous. E.g.: using <= in place of >=, etc.
 Run-time error: The error is encountered at execution stage of the program development.
E.g.: divide by zero, memory overflows, etc.

Java Arrays
An array is a group of variables, all of the same data type that is referred to by a single name. The
values in the group occupy contiguous locations in the computer memory, i.e. the data are stored one
next to each other in the computer memory. Each element in the array is identified by the array name
and a subscript pointing to the particular location within the array.
Score
20 40 10 50 30

Score[0] Score[1] … Score[4]

Types of Array:
(i) One (Single) dimensional array: with a single row or column.
(ii) Two-dimensional array: with more the one row and column.
Creating one-dimensional array:
The general syntax for creating an array is:

element-type[] arrayName; // declares the array.


arrayName = new element-type[n]; //allocates storage for n elements.

As with single objects, both the declaration and allocation can be combined in a single declaration
with initialization as shown below:

element-type[] arrayName = new element-type[n];

Note: element-type could be any of the primitive data type such as int, float, double, char, etc.
22
Examples:

float[] x; //declares x to be a reference to an array of floats…


x = new float[8]; //allocates an array of 8 floats, referenced by x.
boolean[] flags = new boolean[5];
double[] myList = new double[10];

Note that we can initialize an array explicitly with an initialization list, like this:

int[] c = {44, 88, 55, 33};


This means:
int[] c;
c = new int[4];
c[0] = 44;
c[1] = 88;
c[2] = 55;
c[3] = 33;

Two-dimensional Array:
A two-dimensional array looks like a matrix as shown below:

34 05 -5
-10 -2 24
15 13 -7

The following are therefore the features of a two-dimensional array:


 It uses two subscripts i.e. [row][column].
 It has grid of rows and columns, with the 1st subscript locating the row and the 2nd subscript
locating the column.
 Java sees a two-dimensional array as a big array containing small arrays. Each row forms an
array of the whole array.
Examples:

Int[][] x = new int[3][5]; //declares a two-dimensional array x of 3 rows & 5 columns.

a[0][2] = 50; // assigns 50 to the element in row 0 column 2 (1st row 3rd column).

23
PRACTICAL EXERCISES
Comparing print() and println() methods Inputting data into Java programs via
command line
public class Ex1{
public static void main(String[] args){ //program to compute average of 3 nos.
int a, b, c, d; import java.util.Scanner;
a = 2; b=4; c=6; d = 8; Class Avg{
System.out.print(a, b); public static void main(String[] args){
System.out.print(c); Scanner input=new Scanner(System.in);
System.out.println(); //Read in data a, b and c
System.out.println(d); System.out.println(“Enter value for a”);
} float a = input.nextFloat();
}
Output System.out.println(“Enter value for b”);
?? float b = input.nextFloat();

Using the Swing Facility System.out.println(“Enter value for c”);


double c = input.nextDouble();
import javax.swing.*;
//program to add two numbers together System.out.println(“Please, what is your
public class Addition{ name?”);
public static void main(String[] args){ String name = input.next();
//declaring ur variables
String fn, sn; double sum = a+b+c;
int num1, num2, sum; double avg1 = sum/3.0;

fn = JOptionPane.showInputDialog(“Enter System.out.println(“Hello ” + name + “\n The


first number: ”); average = ” + avg1+ “\nBye Bye…”);
sn = JOptionPane.showInputDialog(“Enter
second number: ”); System.exit(0);
}
num1=Integer.parseInt(fn); }
num2=Integer.parseInt(sn);
sum = num1 + num2; Output
??
JOptionPane.showMessageDialog(null, “The sum
= ” + sum, “Result”, Exercises:
JOptionPane.PLAIN_MESSAGE); (1) Write a program to compute user’s year of
birth. (Hint: inputs are user‟s age now and the current
System.exit(0); year e.g. 2016)
}
} (2) Write a program to compute the area of a
circle using the formula:
Output
?? (Hint: use Math.PI for π in your code)

(3) Write a program to compute the square,


square root and cube root of a numeric values
entered by the user.

24
Program to print the constants e and π, absolute A sample method to compute factorial of a
of -1234, cos(π/4), sin(π/2), tan(π/4), ln(1), eπ and number.
five random double numbers between 0.0 and
1.1… public int facto(int x){
int ans = 1;
public class MathApp{ for (int i=2; i<=x; i++){
public static void main(String[] args){ ans = ans * i;
System.out.println(“Math.E = ” + Math.E); }
System.out.println(“Math.PI = ” + Math.PI);
System.out.println(“Math.abs(-1234) = ” + return ans;
Math.abs(-1234)); }
System.out.println(“Math.cos(Math.PI/4) = ”
+ Math.cos(Math.PI/4)); Output
System.out.println(“Math.sin(Math.PI/2) = ” + ??
Math.sin(Math.PI/2)); Program to illustrate different arithmetic
System.out.println(“Math.tan(Math.PI/4) = ” + operators
Math.tan(Math.PI/4));
System.out.println(“Math.log (1) = ”+ public class Arith{
Math.log(1)); public static void main(String[] args){
System.out.println(“Math.exp(Math.PI) = ” + int m=25; int n=7;
Math.exp(Math.PI)); System.out.println(“m = ” + m);
System.out.println(“The first five Random System.out.println(“n = ” + n);
numbers from 1 to 100 are …” ); int sum = m+n;
System.out.println(“m + n = ” + sum);
//To generate random numbers… int diff = m-n;
for (int i=0; i<5; ++i) System.out.println(“m - n = ” + diff);
int prod = m*n;
System.out.println(Math.floor(Math.random()*100) System.out.println(“m x n = ” + prod);
+ “ ”); int quotient = m/n;
} System.out.println(“m / n = ” + quotient);
} int remda = m%n;
System.out.println(“m % n = ” + remda);
Output }
?? }
Using printf() method
Output
public class OpOcHex{ ??
public static void main(String[] args){
Exercises:
System.out.printf(“%d\n”, 26); (1) Write a program to compute the area and
System.out.printf(“%e\n”, +0.000026); perimeter of any plane shape and format your
System.out.printf(“%d\n”, -26); outputs to only 2 decimal places.
System.out.printf(“%o\n”, 26);
System.out.printf(“%x\n”, 26); (2) Write a program to compute the formula:
System.out.printf(“%X\n”, 26); ( )

}
} (3) Write a program to print integer numbers
from -100 to 100. The program should also print
Output even, odd and prime integers within that range.
??

25
Check out the output of this code Formatting output with Class Formatter

public class CheckOut{ import java.util.Formatter;


public static void main(String[] args){ import javax.swing.JoptionPane;

System.out.printf(“%#o\n”, 31); public class FormatterTest{


System.out.printf(“%#x\n”, 31); public static void main(String[] args){
System.out.printf(“%+09d\n”, 452);
System.out.printf(“%09d\n”, 452); //create Formatter and format output
System.out.printf(“%9d\n”, 452); Formatter formatter=new Formatter();
System.out.printf(“%,d\n”, 58625); formatter.format(“%d = %#o = %#X”, 10, 10,
System.out.printf(“%, .2f”, 58625); 10);
System.out.printf(“%, .2f”, 12345678.9);
} //display output in JOptionPane
} JOptionPane.showMessageDialog(null,
formatter.toString());
Output }
?? }
IfElse example
Output
public class IfElse{ ??
public static void main(String[] args){ Ternary operator sample
int testscore = 76;
char grade; public class OpSample{
if (testscore >= 90){ public static void main(String[] args){
grade = „A‟; char aChar = „ayomide‟;
} elseif (testscore >= 80){ //if else option
grade = „B‟; if (Character.isUpperCase(aChar)){
} elseif (testscore >= 70){ System.out.println(aChar + “ is upper
grade = „C‟; case”);
}else{ }else{
grade = „F‟; System.out.println(aChar + “ is lower
} case”);
System.out.println(“Grade = ” + grade); }
}
} //ternary option
System.out.println(“\n\n”);
Output System.out.println(“Ternary operator
?? output\n”);
Exercises:
(1) Write a program to solve for the roots of any System.out.println(aChar + “ is ” +
quadratic equation using the formula: (Character.isUpperCase(aChar)? “ upper ” : “
lower ”) + “case”);

}
}
(2) Write a program to add numbers from 1 to N
together, such that if the next number to be added Output
is divided by 2 and the remainder is not equal to ??
zero, it should be added up, else it should be
discarded from the summation. (Try using the
continue keyword)

26
Using SwitchCase statement Program to compute the times table from 1 to
10
//program to determine if a year is leap year...
import java.util.Scanner; class Times{
class LeapYr{ public static void main(String[] args){
public static void main(String[] args){
Scanner inp=new Scanner(System.in); for (int i=1; i<=10; i++){
//Read in data month and year for (int j=1; j<=10; j++){
System.out.println(“1 – Jan, 2 – Feb … 12 - Dec”); int timesAns = i * j;
System.out.println(“|” +timesAns+“\t”);
int month, yr; }// End of innermost loop

System.out.println(“Please, enter the month”); System.out.println(“________________”);


month = inp.nextInt(); }// End of outermost loop
System.out.println(“Please, enter the year”); }// end of main
month = inp.nextInt(); }// end class

switch (month) { Output


case 1: ??
case 2:
Array example
if (((yr%4==0) && !(yr%100 ==0))
|| (yr%400 ==0))
public classArrayEx{
System.out.println(yr +“ is leap year with 29 days
public static void main(String[] args){
in Feb”);
int [] c={44, 88, 55, 33);
else
System.out.println(“2nd Element = ” +
System.out.println(yr +“ is not leap year with 28
c[1]);
days in Feb”); break;
case 3:
//This is a ragged 2-dimensional array
case 12: int numDays = 31; break;
int [][] a= {{77,33,88},
case 11: int numDays = 30; break;
{11,55,22,99},
default: System.out.println(“Wrong input. Bye!”);
{66,44}
break;
};
}// end of switch stmt
for (int i=0; i<a.length; i++){
}// end of main method
for (int j=0; j<a[i].length; j++)
}// end of class
System.out.print(“\t”+a[i][j]);
System.out.print();
}
Exercises: }
(1) Weather conditions in some regions in Nigeria }
were studied and the following data were obtained:
RegID State Temp Rainfall Pressure Output
o
C (mm3) (bar) ??
SW01 Oyo 23.8 5.2 3.0 Exercises:
SW02 Ogun 28.5 6.8 5.9 (2) Assuming the Rank Correlation Coefficient
SW03 Lagos 20.5 12.7 4.8 Rc formula is given by:
SW04 Ondo 23.7 10.6 2.8
SW05 Ekiti 26.6 7.8 2.9
Write a code to compute the average values of data
for each region from the data above assuming the
data are stored in a two-dimensional array. Where X, Y and Z are means.
Write a code to compute Rc in the data given
above.
27
28

You might also like