0% found this document useful (0 votes)
4 views45 pages

02 Java Program Structure Pr

The document provides an overview of Java programming, covering basic syntax, structure, and the creation of applications and applets. It explains essential concepts such as case sensitivity, class and method naming conventions, and the importance of the main method. Additionally, it discusses input/output methods, including command line and GUI interactions, along with examples of Java code for simple applications.

Uploaded by

rigiiih10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views45 pages

02 Java Program Structure Pr

The document provides an overview of Java programming, covering basic syntax, structure, and the creation of applications and applets. It explains essential concepts such as case sensitivity, class and method naming conventions, and the importance of the main method. Additionally, it discusses input/output methods, including command line and GUI interactions, along with examples of Java code for simple applications.

Uploaded by

rigiiih10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 45

JAVA PROGRAM

STRUCTURE

10/15/2024 MUNYAO 1
import java.util.Scanner; .
public class Essentials
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int value1 = 0;
System.out.println("Enter a number:");
value1 = in.nextInt();
int value2 = 0;
System.out.println("Enter a second number:");
value2 = in.nextInt();
int sum;
sum = value1 + value2;
System.out.println("Sum = " + sum);
}
} MUNYAO 2
OBJECT ORIENTED
PROGRAMMING
• Introduction
• Java can be used to develop two types of
programs, Applications and Applets. In
this topic we shall create a simple
application and a simple applet.

3
Basic Syntax:
• 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 word's 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()
10/15/2024 MUNYAO 4
Basic Syntax:
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 (Remember Java is
case sensitive) and append '.java' to the end of the name
(if the file name and the class name do not match your
program will not compile). Example : Assume
'MyFirstJavaProgram' is the class name, then the file
should be saved as'MyFirstJavaProgram.java'
public static void main(String args[]) - Java program
processing starts from the main() method, which is a
mandatory part of every Java program.
10/15/2024 MUNYAO 5
Creating a simple Java Application

• To create a java program, you will need to do the following:


• Create a source file. A source file contains text, written in
the Java programming language. You can use any text editor
to create and edit source files.
• Compile the source file into a bytecode file. We use the Java
compiler –called javac to converts your source file into a
bytecode file.
• Run the program contained in the bytecode file. The Java
interpreter installed on your computer implements the Java
VM. This interpreter takes your bytecode file and carries out
the instructions by translating them into instructions that
your computer can understand.
10/15/2024 MUNYAO 6
Create a Source File.
Source files are created using editors such as notepad. To
create the source file for our first application we need to
type the following code and save it in Notepad.
NB: Java is case sensitive hence capitalize consistently.
/** The “Welcome” class implements an application that
displays "Welcome to Java!" to the standard output. */
public class Welcome {
public static void main (String args []) {
// Display " Welcome to Java!"
System.out.println ("Welcome to Java");
}
10/15/2024 MUNYAO 7

}
First Java application
public class HelloWorld
{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class

10/15/2024 8
CREATING JAVA
APPLICATION
• Creating the source file.
// first java application
//prints the Hello world!
class HelloWorld {
// main method begins execution of Java application
public static void main (String args[])
{
System.out.println("Hello World!");
} // end method main
} // end class Welcome1 9
Explanation of the code
• Java source file must have the same name
as the class they define.
• Must have a .java extension
• Java is case sensitive
• Saved in a folder probably in C:
• // single line comment
• /* This is a multiple line comment. It can
be split over many lines */
10/15/2024 10
• /**-----*/ Javadoc comments. The javadoc
utility program reads Javadoc comments
and uses them to prepare your program’s
documentation
• Class definition / Declaration (it has class
keyworld and class identifier)
• Main method signature(Java application
begin executing at main)
10/15/2024 AI 11
• Every Java standalone application must contain a
main method whose signature is as shown
public static void main( String args[] )
{ statements;
}
• This contains three modifiers
– Public – indicates that the method can be called by
any method
– Static – indicates that the main method is a class
method and that only one main method can exist
– Void – indicates that the main method does not return
any value.
10/15/2024 MUNYAO 12
Cont….
• The left brace, ({), begins the body of the
method defination.
• Right brace, ({), must end the method
definition’s body
• The statement System.out.println(“”) is a
method that instructs the computer to print.
• Every statement must end with a
semicolon(;)

10/15/2024 MUNYAO 13
10/15/2024 MUNYAO 14
Java program
public class Book {
public static void main(String[]args)
{
String title="Introduction to Java";
String author="Stephen John";
int noOfPages=300;
System.out.println("The name of the book is "+title);
System.out.println("The AUTHOR of the book is
"+author);
System.out.println("The book has "+noOfPages+"
pages");
15
}
class Person{
public static void main(String [] args)
{
int age=29, height=2, weight=72;
String FirstName="John", LastName="Mwaura";
System.out.println("My first name is "+FirstName+" and my
last name is "+LastName+".");
System.out.println("I am "+age+" years old, and weighs
"+weight+" Kgs.");
System.out.println("I am "+height+" metres tall");
}
}
16
escape character.
Escape Description
sequence

\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor at the beginning of the current
line—do not advance to the next line. Any characters output after the
carriage
return overwrite the characters previously output on that line.

\\ Backslash. Used to print a backslash character.


\" Double quote. Used to print a double-quote character. For example,
System.out.println( "\"in quotes\"" );
Displays "in quotes"

17
Explanation of Java codes
All java programs assume a structure similar to the following:
1. package packagename;
2. import java.packagename.*;
3. [access modifier ] class classname[extends
superclassname][implements interfacenamee] {
4. //member variable declarations.
5. type variable name;
6. //method implementations.
7. [access modifier] returntype methodname(method
parameters)
{ statements in method block;
}// end of method defination
18
}//end of class definition.
1 The package statement
The package keyword is used in the package statement used
to create or define the package to which a class belongs.
It is optional. When left out, the program is automatically
placed in the default package. In java language, packages
are used to group classes just like the way libraries are
used to group C functions.
2 The import statement
It is used to import a package, i.e., a group of related classes
that the program requires to perform the task for which it
is being developed.
Examples 19
– import java.applet.*;
• This statement imports the java applet package that
provides the classes necessary to communicate with an
applet.
– import java.awt.*;
• This statement imports the awt-abstract windowing toolkit
that provides the java GUI components and containers and
the Graphics class that allows objects to draw simple on
screen shapes and text.
– import java.io. *;
• This package provides for system input and output through
data streams. MUNYAO 20
– import java. Lang.*;
• It provides classes that are fundamental to the design of
the Java programming language. It is imported
automatically, i.e , the user does not have to import it
explicitly.
– import java.awt.event.*;
• This package provides the events required by all event
handling programs.

10/15/2024 MUNYAO 21
3 Class definition
After the import statements we have the class definition for
example:
public class HelloWorld extends Applet{
class definition block
}
The extends key word is used to inherit the properties of an
existing class(Applet class) into the class being
defined(Hello class).

10/15/2024 MUNYAO 22
4 Methods and constructors
Within the class there can be several methods and
constructors. However, for any program to be a
standalone it should have the main method. Example:
public static void main (String args [])
{
method block statements;
}
• The words public and static used in the main method
above are referred to as modifiers.

10/15/2024 MUNYAO 23
Modifiers
• They are special keywords that modify the
definition of a class, method or variable.
Examples of these modifiers are:
– static
– final
– private
– public
– protected
– Abstract

10/15/2024 MUNYAO 24
2.4.1 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. When used to modify an
inner class it makes the class a top-level class.
Example:
Public static void main (…//

10/15/2024 MUNYAO 25
2.4.2 Final
The final modifier is applicable to classes, methods and
variables.
It is used to make a variable a constant.
Example:
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.

10/15/2024 MUNYAO 26
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.
Example:
private int number; //would only be visible within the class it
is defined.

10/15/2024 MUNYAO 27
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.
Example: protected int Number;
Public - it is used to makes members accessible universally.
Example: 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 (equivalent to them all
being C++ friends) but inaccessible outside the package.
10/15/2024 MUNYAO
Note that this is not the same as the members being 28

declared private.
Abstract:
This modifier is applicable to classes and methods. An
abstract class must be extended but cannot be instantiated,
that is, an object cannot be created from it. Abstract
methods on the other hand have no implementation in the
class where they are defined. They must be implemented
in the subclass of the class in which they are defined
otherwise, the subclass must also be declared abstract.
Within the method block, there are several statements that
form the rest of the program. The most important include
the input and output streams.

10/15/2024 MUNYAO 29
10/15/2024 MUNYAO 30
INPUT OUTPUT
STATEMENTS
• Methods of Reading values from keyboard
• Buffered Reader
• JOptionpane

•Scanner
• Output Data values on the screen

10/15/2024 31

MUNYAO
Methods of Reading values from
keyboard
• Most systems are interactive and use some
type of user interface to support users in
using their system.
• Java enables both the Command Line
Interface (CLI) as well as the more useable
Graphical User Interface (GUI’s).

10/15/2024 MUNYAO 32
Buffered Reader
• A program is run from the command line and
interacts with the user in the command-line
environment.

10/15/2024 MUNYAO 33
import java.io.*;
class InputTest{
public static void main(String args[])throws IOException
{
BufferedReader input=new BufferedReader (new
InputStreamReader(System.in));
String strnum1; String strnum2;
int num1; int num2; int sum=0;
System.out.println("Enter first Number:");
strnum1=input.readLine();
num1=Integer.parseInt(strnum1);
System.out.println("Enter second Number:");
strnum2=input.readLine();
num2=Integer.parseInt(strnum2);
sum=num1+num2;
System.out.println("sum="+sum);
GUIs
• The provision of a Graphical User Interface, as
opposed to the older style Command Line
Interface (CLI), is one of the principal
characteristics of modern software
• The Java platform provides packages for the
construction of such interfaces

10/15/2024 MUNYAO 35
GUIs
• The original Java GUI library was AWT (Abstract
Windowing Toolkit)
– found in the package java.awt
• From Java 1.2 a new library called Swing was introduced
which replaces many AWT classes
– found in the package javax.swing (note the ‘x’)
• The Standard Widget Toolkit (SWT) is a replacement for
both AWT and Swing
• This makes it fast and well-integrated with the host
system GUI
10/15/2024 MUNYAO 36
A first GUI project
• The class User, has provided us with simple
pop-up dialogs for input and output
Button Demo

Click Me!
JButton button

Jframe frame

Container contentPane (actually a JPanel)

10/15/2024 MUNYAO 37
import javax.swing.JOptionPane;
public class InputBox
{
public static void main(String args[])
{
String fnum, snum;
int num1, num2, sum;
fnum = JOptionPane.showInputDialog("Enter the first Number");
snum=JOptionPane.showInputDialog("Enter the second Number");
num1=Integer.parseInt(fnum);
num2=Integer.parseInt(snum);

sum=num1+num2;
JOptionPane.showMessageDialog(null, "the Sum is :" + sum,
"Addition Results", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}}
import javax.swing.JOptionPane; // import class JOptionPane
.
public class Welcome4 {

// main method begins execution of Java application


public static void main( String args[] )
{
JOptionPane.showMessageDialog(
null, "Welcome\nto\nJava\nProgramming!" );

System.exit( 0 ); // terminate application

} // end method main

} // end class Welcome4


10/15/2024 AI 39
Area Of cicle
import javax.swing.JOptionPane;
public class AreaOfCircle
{
public static void main(String args[])
{
String fnum;
final double PI=3.14285;
int radius;
double area=0;
fnum = JOptionPane.showInputDialog("Enter the radius of the circle.");
radius=Integer.parseInt(fnum);
area=PI*radius*radius;
JOptionPane.showMessageDialog(null, "The area of a circle whose radius is"
+ radius + " is" + area, "Area of a CIRCLE",
JOptionPane.PLAIN_MESSAGE); 40
System.exit(0);
Scanner
• To read in the input that the user has entered, use the Java
object Scanner. You will have to use an import statement
to access the class java.util.Scanner
• import java.util.Scanner;
• •To initialize a Scanner, write:
• Scanner in = new Scanner(System.in);
• •To read the next string from the console:
• String input = in.next();
• •To read the next integer:
• int answer = in.nextInt();
10/15/2024 MUNYAO 41
A Scanner object contains the following
methods for reading an input:
• next(): reading a string. A string is delimited by spaces.
• nextByte(): reading an integer of the byte type.
• nextShort(): reading an integer of the short type.
• nextInt(): reading an integer of the int type.
• nextLong(): reading an integer of the long type.
• nextFloat(): reading a number of the float type.
• nextDouble(): reading a number of the double type.

10/15/2024 MUNYAO 42
import java.util.Scanner; // Scanner is in java.util
public class ScannerTest {
.
public static void main(String args[]) {
// Create a Scanner
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int intValue = scanner.nextInt();
System.out.println("You entered the integer " + intValue);
System.out.print("Enter a double value: ");
double doubleValue = scanner.nextDouble();
System.out.println("You entered the double value " + doubleValue);
System.out.print("Enter a string without space: ");
String string = scanner.next();
System.out.println("You entered the string " + string);
}
}
10/15/2024 MUNYAO 43
10/15/2024 MUNYAO 44
END
10/15/2024 MUNYAO 45

You might also like