0% found this document useful (0 votes)
11 views8 pages

Introduction to Java Programming Concepts

Java, originally named Oak, is an object-oriented programming language designed for simplicity, robustness, and portability, allowing programs to run on various operating systems. It features a Java Virtual Machine (JVM) for execution and an Application Programming Interface (API) for common tasks, with different editions for client-side and server-side applications. The document outlines the structure of Java programs, the use of classes and methods, input/output operations, and the importance of comments and keywords in coding.
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)
11 views8 pages

Introduction to Java Programming Concepts

Java, originally named Oak, is an object-oriented programming language designed for simplicity, robustness, and portability, allowing programs to run on various operating systems. It features a Java Virtual Machine (JVM) for execution and an Application Programming Interface (API) for common tasks, with different editions for client-side and server-side applications. The document outlines the structure of Java programs, the use of classes and methods, input/output operations, and the importance of comments and keywords in coding.
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

INTRODUCTION

Java was originally called Oak but upon discovering there was another programming language with the same
name, the development team renamed it to Java after one of the brands of coffee. The language grew out of a
project to develop a personal digital assistance [PDA], i.e., a device that was intended to control all electronic
devices used in homes.
Java is a true OO language and therefore the underlying structure of all Java programs is classes. Generally, a
class serves as a template or blueprint for an object and behaves like a basic data type “int”. It is therefore
important to understand how the fields and methods are defined in a class and how they are used to build a Java
program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism.

Characteristics of java
Java attempts to overcome the limitations of its predecessors and as such it is designed to be:
i). Simple: - Java has much in common with C++ but does not have some features that are present in
C++. These features make C++ very powerful but are also very dangerous when in the wrong
hands.
ii). Object oriented: - In java, data and process are encapsulated together to provide objects that have
both state [data] and behavior [process]. This makes it easier for the programmer to model real
world things [objects].
iii). Distributed: - Java is designed for network programming and can easily work with common
internet protocols such as HTTP (hypertext transfer protocol) and FTP (file transfer protocol). It
provides facilities to write systems where programs are distributed across many computers.
iv). Robustness: - A robust program is one that does not behave unpredictably or fail due to
programmer error. Java is more robust compared to other languages because it does not allow
programmers to have direct access to the memory. This is so because pointers are not used in java.
v). Secure: - Java has inbuilt security systems that ensure a code once written is not easy to tamper
with. There are also a number of restrictions placed on what applets can do when they are running
on a remote machine.
vi). Multithreaded: -Java allows many simultaneous activities in one program via the Thread class.
The major benefits are better interactive performance and real-time behavior. For example, images
can be loaded with one thread, while user accesses the HTML information on a Web page.
vii). Architecture neutrality/Platform independent/portability: - Java programs once written can be
run on different operating systems. This is made possible by combining compilation and
interpretation of the source code.

JAVA PLATFORM
It refers to both hardware and software;
 Java Virtual Machine (JVM): A layer above the physical hardware of any given machine on which java
code executes. This makes Java platform independent. The JVM is an imaginary machine that interprets the
byte code to run on a specific hardware.
 Application Programming Interface (API): A set of inbuilt modules to do common tasks. Java library is
made of packages which in turn are made of classes for common repetitive tasks. Programmers reuse the
packages making programming in java easy.

Object oriented Programming Page 1 of 8


JDK Editions
 Java Standard Edition: - It is used to develop client-side standalone applications or applets.
 Java Enterprise Edition: - It is used to develop server-side applications such as Java servlets and Java Server
Pages.

Java Programming Environments


Like other Languages, there are three environments:
 Editor – Source code written and edited using text editor. File saved with .java extension
 Compiler – Source code translated into byte code and saved in a file with .class extension. The byte code
can be executed on many different kinds of computers. javac program is used to compile.
 Execution – java launcher is used to interpret and execute the program.
In command line, the three environments are separate. The following diagram illustrates the Java programming
process

Java IDE Tools


An IDE combines the three environment into one. The following are some common IDEs :
 Borland JBuilder
 JCreator
 Eclipse by IBM
 BlueJ
 NetBeans by Sun Microsystems, etc.

Java Program Types


 Application: - Standalone Java program that can run independent of any Web browser
 Applet: - Java program that runs within a Java-enabled Web browser
 Servlet: -Java software that is loaded into a Web server to provide additional server functionality similar to
CGI programs

Structure of Java programs


All java programs assume a structure similar to the one shown below.
package packagename;
import [Link].*;
[access modifier] class classname [extends superclassname][implements
interfacenamee]
{
//member variable declarations.
type variable name;
//method implementations.
[access modifier] returntype methodname(method parameters)
{
statements in method block;
}// end of method defination
}//end of class definition.
The package keyword is used in the package statement to create or define the package to which a class belongs.
It is optional and when left out, the program is automatically placed in the default package.

Object oriented Programming Page 2 of 8


Generally, every executable Java program consists of a class that contains a method named main, which
contains the statements (commands) to be executed

Example
Create a Java application program that displays Welcome to Java Programming

public class Welcome {


public static void main(String[] args) {
[Link]("Welcome to Java Programming");
}
}

Explanations
The class is made up of:
 The class name-Welcome, which is decided by the programmer.
 The public prefix, which means that the class can be visible to all other classes. If we omit this prefix the
class will only be visible within its own package.
 The class body, which is surrounded by braces (curly brackets {}). Everything between the opening and
closing brace belongs to that class and is what is referred to as the scope of the class. A class can see
everything that falls within its scope. In this example the only thing that is in the class is a method called
main.
Note that the Welcome class must be saved in a file called [Link] with exactly the same mix of upper
and lower case letters this is required for public classes and makes it easier to find a particular class later. The
extension .java is required by the compiler and hence must be included.

main Method
The main method is always the first to be executed when a class is run by the java virtual machine and an
application must have at least one class with a main method in order to runl. The method is declared public
which means it is part of the public interface of the class and also static, which means it, belongs to the class
rather than to individual objects. Its return type is void meaning that it does not return any value. Its parameter
list (“String [] args) means that we may send one or more string objects to this method as parameters.
Compile the Source File.
To compile the source file:
i). Start Dos Prompt
ii). If the prompt is not C :\> then change it to C:\>.
iii). Change to the directory where you saved your file.
iv). Type the following at the prompt:
set path=%path%; C:\Program Files\Java\jdk1.8.0_60\bin
Then press Enter. Notice that this tells the system where to find JDK programs.
v). Type javac Welcome. java and press Enter.
vi). If any errors are reported, debug the program and save it before attempting to compile it again. Otherwise,
the code will now be compiled into a Class and you may run it.
Run the Program
In the same directory, enter at the prompt:
java Welcome
Then press enter key. If your program displays Welcome to Java Programming then it Works.
Note: - It is possible to make the path setting permanent by editing the "Environment variables"

Object oriented Programming Page 3 of 8


ANATOMY OF A JAVA PROGRAM
Comments
A comment is an explanatory text that makes the code readable. Java provides three different types of comment
syntax:
i).
/**
Text here
*/
ii).
/*
Text here
*/
iii). // Text here

The first type is preferable because it is used by javadoc-an automatic class documenting tool that works with
java code. The third syntax is used for short comments and the end of the comment is the end of the line on
which it appears. This type of comment is ignored by javadoc hence may not be appropriate for writing major
comments.
Using comments
Comment may be placed:
– at the top of each file (also called a "comment header"), naming the author and explaining what the program
does
– at the start of every method, describing its behaviour
– inside methods, to explain complex pieces of code

Package
This is a group of related classes that the program requires to perform the task for which it is being developed.
Most Java programmers take advantage of the rich collections of existing classes in the Java class libraries,
which are also known as the Java APIs (Application Programming Interfaces). One can import a specific
class or even an entire package. The following are some useful packages used in Java:
 [Link] - provides for system input and output through data streams.
 [Link] - Provides classes that are fundamental to the design of the Java programming language. It is
imported automatically
 [Link] - Abstract Windowing Toolkit that provides the java GUI components and containers and the
Graphics class.
 [Link] - This statement imports the java applet package that provides the classes necessary to
communicate with an applet.

Syntax:
import [Link].*;
This imports all the classes in a package by use the wild character (*).It is possible to import a specific class by
replacing the * with the class name as shown below
import [Link]; //imports the Graphics class from the awt package.

Keywords
Reserved words or keywords are words or identifier that have a specific meaning to the compiler and cannot be
used for other purposes in the program. The following is a list of Java keywords:
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
Object oriented Programming Page 4 of 8
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
Notice that Java is a case-sensitive language and the keywords must be in lower case

Modifiers
They are special keywords that modify the definition of a class, method or variable. Examples of these
modifiers are:
i). static: - It is used to declare class variables and class methods. Class variables are those that
are referenced by the class name rather than the object name.
ii). final: - The final modifier is applicable to classes, methods and variables. It is used to make a
variable a constant.
syntax:
final double PI=3.14159
When used to modify a class, it prevents the class from being extended (inherited) and modifies a method so
that it cannot be redefined in a subclass.
iii). private, public and protected
These are known as access modifiers since they allow one to control the visibility and access to variables
and methods inside your class
private: - This modifier is applicable to methods and variables. It makes them visible/accessible only within
the class in which they are defined.
Syntax:
private int number; //would only be visible within the class it is defined.

protected: - It is applicable to methods and variables. When used it makes the member visible to the
package within which it is defined and to subclasses of the class within which it is defined that could be in
any other package.
syntax: protected int number;
public: - it is used to makes members accessible universally.
syntax: public class HelloWorld{}
Without an explicit access specifier, member defaults to “friendly,” which means that it is accessible to
other elements in the same package but inaccessible outside the package. Note that this is not the same as
the members being declared private.

Statements
A statement represents an action or a sequence of actions. Every statement in Java ends with a semicolon (;).
Blocks
A pair of braces in a program forms a block that groups components of a program.

public class Test {


public static void main(String[] args) { Class block
[Link]("Welcome to Java!"); Method block
}
}
Classes
A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
The class is the essential Java construct. To program in Java, you must understand classes and be able to write
and use them. Generally a Java program is defined by using one or more classes.

Object oriented Programming Page 5 of 8


Methods
A method is a collection of statements that performs a sequence of operations. e.g. println() is a collection
of statements that performs a sequence of operations to display a message on the console.

INPUT/OUPUT IN JAVA
Designing the User Interface
A user interface is a program’s input and output capabilities. An input operation is action that transfers data
from the user to the computer’s main memory while an output operation is action that transfers data from main
memory to an output device. There are two types of interface: command-line and graphical user interface (GUI)

Command-Line Interface
In a command-line interface or console interface input is taken from the keyboard and output is directed to the
console.

Input and Output Streams


In Java, input and output are handled by streams as shown below

Scanner for Input from Console


In JDK 1.5, a [Link] class was introduced to handle user input in console application. This class
enables us to read string, integer, long, etc in the console application. The following is a table showing various
methods used with Scanner objects when inputting primitive datatypes

Numeric and String Methods


Method Returns
int nextInt() Returns the next token as an int. If the next token is not an integer,
InputMismatchException is thrown.
long nextLong() Returns the next token as a long. If the next token is not an integer,
InputMismatchException is thrown.
float nextFloat() Returns the next token as a float. If the next token is not a float or is out of range,
InputMismatchException is thrown.
double nextDouble() Returns the next token as a double precision float. If the next token is not a float or
is out of range, InputMismatchException is thrown.
String next() Finds and returns the next complete token from this scanner and returns it as a
string; a token is usually ended by whitespace such as a blank or line break. If not
token exists, NoSuchElementException is thrown.
String nextLine() Returns the rest of the current line, excluding any line separator at the end.

void close() Closes the scanner.

Object oriented Programming Page 6 of 8


Example
Write a Java program that inputs two numbers using the console window and then computes and displays the
sum

import [Link];
public class Compute{
public static void main(String[] args) {
Scanner reader=new Scanner([Link]);
int number1, number2, sum;
[Link]("Enter the first number:");
number1=[Link]();
[Link]("Enter the second number:");
number2=[Link]();
sum=number1+number2;
[Link]("Sum is :"+sum);
}
}

Displaying Text with printf


A new feature of JSE 5.0 is the [Link]() method for displaying formatted data. Method printf's first
argument is a format string that may consist of fixed text and format specifiers, while second is vector of
elements to be [Link] specifiers begin with a percent sign (%) and are followed by a character that
represents the data type as shown in the table below:

type Input String result

%d signed int signed decimal integer

%u unsigned int unsigned decimal integer

%o unsigned int unsigned octal integer

%x, %X unsigned int unsigned hexadecimal integer, lowercase or uppercase

%f float real number, standard notation

%e, %E float real number, scientific notation (lowercase or uppercase exponent marker)

same format as %f or %e, depending on the value. Scientific notation is used only if the
%g, %G float exponent is greater than the precision or less than -4.
%s string String

%c char Character

%p object object identity hash code (i.e., pointer value), in unsigned hexadecimal

DIALOGS
You can use the showInputDialog method in the JOptionPane class to get input at runtime. When this method is
executed, a dialog is displayed to enable you to enter an input value.
Syntax
String string = [Link](null, prompt, title,
JOptionPane.QUESTION_MESSAGE));

The first argument can always be null. The second argument is a string that prompts the user. The third
argument is the title of the input box. The fourth argument can be JOptionPane.QUESTION_MESSAGE, which
causes the icon ( ) to be displayed in the input box.
Object oriented Programming Page 7 of 8
Note: There are several ways to use the showInputDialog method. E.g.
[Link](prompt); where prompt is a string for the prompting message.

Converting Strings to Numbers


The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns
"123". You have to convert a string into a number to obtain the input as a number. To convert a string into an
int value, use the parseInt method in the Integer class, as follows:

int intValue = [Link](intString);


where intString is a numeric string such as "123".

To convert a string into a double value, use the parseDouble method in the Double class as shown below:
double doubleValue = [Link](doubleString);

Notice that the Integer and Double classes are both included in the [Link] package, and thus are
automatically imported.

Message box dialog


Displays a message on a dialog with an OK button.
Syntax:
showMessageDialog(<parent>, <message>)

Example
Write a Java program that inputs two integer numbers using Input dialogs and then computes for the sum and
average. Your program should display the sum and average using message dialog.

import [Link];
public class Numbers{
public static void main(String[] args) {
String firstNumber= [Link]("Enter the first number");
//Convert string to integer
int number1 =[Link](firstNumber);
String secondNumber= [Link]("Enter the second
number");
//Convert string to integer
int number2 =[Link](secondNumber);
int sum=number1+number2;
double average= (double)sum/2;
[Link](null,"Sum is :" + sum + " Average : "
+average);
}
}

Confirm dialog
Syntax
showConfirmDialog(<parent>, <message>)

Displays a message and list of choices Yes, No, Cancel; returns user's choice as an int with one of the following values:
 JOptionPane.YES_OPTION
 JOptionPane.NO_OPTION
 JOptionPane.CANCEL_OPTION

Object oriented Programming Page 8 of 8

You might also like