Java Programming

By N Michael

Chapter Contents
1 Literals
2 Escape Codes
3 Primitive Data Types
4 Comparison operators
5 Logical operators
6 Assignment
7 Branches and Loops
8 ARRAYS
9 Formated Printing (Floating Point)
10 Casting and Converting Objects and primitive types
11 Math Class
12 String Class Functions
13 StringBuffer Class Functions
14 Graphics
15 Fonts and Drawing Text
16 Colour
17 Get Input From Users
18 Send Output to User
19 Man Machine Dialog
20 Creating Classes     
  1. The THIS pointer
  2. Method and Variable Access Control (Modifiers)
  3. Method Signatures(Method Overloading)
  4. Passing Values and Objects to methods
21 Casting and Converting Objects and Primitive types
22 Applets and Applications
23 APPLETS
24 Source Files
25 Wrapper Classes
26 Low-Level System-Access Classes
27 Extending Classes (Inheritance)
28 Poly Morphasis
29 Object Casting Rules
30 Abstract Classes
31 Final Classes
32 Interfaces
Index
Samples Sample Applications and Applets
Feedback Tell Nico What you think of his Java Page

 


1 Literals

Numeric Literals are are used to indicate Octal Hexadecimal values

Value Means  
0X 0H Hexadecimal
012 AH Octal
0777 FFH Octal

Top of Page


2 Escape Codes

Character Literals are are used to insert special characters into Strings

\n New line
\b Backspace
\r Carrage return
\t Tab
\f Form feed
\\ Back slash
\’ Single quote
\" Double quote
\ddd Octal
\xdd Hex
\udddd Unicode
   

Top of Page


3 Primitive Data Types

Integer byte  
  short  
  int  
  long  
Floating Point float  
  double  
Boolean boolean  
character char  
     

 

IEEE754 floating point Specification

strictfp

 

Top of Page


4 Comparison operators

== Is equal
!= Not equal
> Greater than
< Smaller than
<= Smaller equal
>= Greater equal
   

 

Top of Page


5 Logical operators

& And
| Or
^ Xor
<< Shift left
>>> Shift right
~ Zero fill shift right
&& And Short Circuit operator (drop out on first false)

 

Top of Page


6 Assignment

=  
+= Plus and assign
-= Minus and assign
/= divide and assign
*= multiply and assign
%= Modulus and assign
^= Xor and assign
&= And and assign
|= Or and assign
<<= Shift left and assign
>>= Shift right and assign
>>>= Zero fill shift right and assign
   
= ++X Prefix increment opperator X is incremented before assignment
= x++ Postfix increment opperator X is incremented after assignment
= --X Prefix decrement opperator X is incremented before assignment
= x-- Postfix decrement opperator X is incremented after assignment

 

Top of Page


7 Branches and Loops

IF Else


if (expression)
{
   some_code_to_execute
}
else if (expression)
{
    some_code_to_execute
}
else
{
   some_code_to_execute
}

 


The nested If

if (expression1)
{
   if (expression2)
    {
        some_code_to_execute
    }
}


Conditional (Tenary) Opperator

myVariable=(BooleanExpression)?TrueReturnExpression:FalseReturnExpression;

 


The Switch statement

switch (expression)
{
   case ConditionalValue1:
                some_code_to_execute
              break; // Leave loop (You must put a break for each Case)        

    case ConditionalValue2:
                some_code_to_execute
             break; // Leave loop (You must put a break for each Case)

    default:
                some_code_to_execute
                break; // Leave loop (You must put a break for each Case)
}

 


The For Loop

for (initialExpression;testCondition;iterationExpression)
{
        some_code_to_execute
}

 


The Nested For Loop

for (initialExpression1;testCondition1;iterationExpression1)
{
        for (initialExpression2;testCondition2;iterationExpression2)
        {
                    some_code_to_execute
        }
}


The While Loop

while (loopconditionExpression)
{
        some_code_to_execute
}


Do while Loop

do
{
       some_code_to_execute

} while (loopconditionExpression)

 


Loops Breaking and continuing

[looptype] 
{ 
    some_code_to_execute;     
    continue // resume executing at top (forcing the next loop iteration) 


    some_code_to_execute; 
    continue Here // resume executing at label HERE 
    some_code_to_execute; 
    break; // Leave loop  


    some_code_to_execute 
    break Here // Leave and continue executing at label HERE 

    some_code_to_execute 


    Here: // label HERE 
    some_code_to_execute 
}

 

Top of Page


8 ARRAYS

 

Are ordered collections of objects.Objects such as Variables or even Strings or even other arrays 
Of the same type

Three methods of putting arrays into you code

Method1

Step 1 Declare Array 
Int [ ] numbers; // Declaring an array Java Style 
Int numbers [ ] // Declaring an array C++ style

Step 2 Define Array 
Numbers = new int [5];

Method 2
Int [ ] Numbers= new int [5]; // combinding the above

Method 3
Int [ ] Numbers={4,6,7,11,14,2,22}; // giving an array initial values

Or

Int [ ] numbers= new int[5]; 
Numbers[4]=23; 
Numbers[3]=32;

Creating Array Variables 

String [] diffucultWords; 
int [] itemsPurchased;

Creating Array Objects 

String [] names = new String[30]; 
int [] itemsPurchased = new int[30];

Multidimentional Arrays 

int coords [][] = new int[12][15]; 
coords [0][1]=21; 
coords[1][4]=36;

Initializing Arrays 

String[] names={"Peter","Jack","John"}; 
int[] numbers={2,4,6,7,8,9};

Creating Array Objects 
Int[] temps = new int[99]; 
Number =new int[]:2,4,5,6,7,}; 

When you use the new keyword all the arrayelementss are automatically initialized

int is initialized to 0 
String is initialized to Null

Determining the upper bound of an Array

int myArray[];  
n=myArray.length; 
for (i=0;i=n;i++) 
{ 
    System.out.println(myArray.length[i]); 
}

Top of Page


9 Formated Printing (Floating Point)

format.applyPattern(printPattern)

0 print a digit or a zero to pad space 
# print a digit or a space 
. Set the decimal point position

NumberFormat.setMinimumIntegerDigits(5);  
NumberFormat.setMaximumIntegerDigits(9);

Format Value Printout
0.00 6.456 006.46
#.## 6.456 6.46
###.0 6.456 6.5
unformatted 6.0 6.0
0.00 6.0 006.00
#.## 6.0 6
###.0 6.0 6.0
unformatted 6564 6564.0
0.00 6564 6564.00
#.## 6564 6564
###.0 6564 6564.0

 

Top of Page


10 Casting and Converting Objects and primitive types

Primitive types 

(typename) value 
(int) (x/y);  
netPrice = (int) Price;

Casting objects 

GreenApple a;

Apple a2; 
a=new GreenApple();

a2 (Apple) a;

 

Top of Page


11 Math Class

Constants 


Math.E = e = 2.718281828459 
Math.PI = 3.14159265359

The Math Class Functions

Function Return Type Argument type
sin Static double double
cos Static double double
tan Static double double
asin Static double double
acos Static double double
atan Static double double
atan2 Static double double a/ double b
round Static long double
round Static int float
ceil Static double double
flour Static double double
rint Static double double
IEEEremainder Static double double a double b
sqrt Static double double
pow Static double double a double b
exp Static double double
log Static double double
random Static synchronised double  
toDegrees Static double double
toRadians Static double double
abs Static int int
abs Static long long
abs Static float float
abs Static double double
min Static int int
min Static long long
min Static float float
min Static double double
max Static int int
max Static long long
max Static float float
max Static double double

 

Top of Page


12 Strings and String Class Functions

 

3 methods to declare strings

Method 1
String hatcolor; // declaring
Hatcolor="Black";// using string

Method 2
String hatColor= "Black";

Method 3
String hatColor= new String("Black");  // Since Strings are objects they can also be decalared as

                                                          //   classes

All strings are allocated to the pool of literal strings
Java strings are imutable ie they have their size set in stone
String Buffers are mutable their sizes can be changed dynamically

Function Return Type Argument type
charAt char String
concat String String
compareTo int String
compareToIgnoreCase int String
endsWith boolean String
equals boolean String
equalsIgnoreCase boolean String
indexOf int String
length int String
replace String String
startsWith boolean String
substring String String
toLowerCase String String
toUpperCase String String
toString String String
trim String String
     

 

Top of Page


13 StringBuffer Class Functions

Function Return Type Argument type Comments
charAt char int index  
capacity int    
length int    
append   object  
append   String  
insert   int offset, String str  
delete   int start , int end  
reverse      
setCharAt   int offset, char ch  
setLength   int len  
       

 

Top of Page


 

14 Graphics

Graphics Coordinate System

 

0,0

20,20

 
60,60

 

Drawing Shapes

public void paint(Graphics g) 
{ 
        //drawing code goes here 
}

Shape Function
   
Line g.drawLine(x1,y1,x2,y2)
Rectangle g.drawRect(x1,y1,x2,y2)
Rounded Rectangle g.drawRoundRect(x1,y1,x2,y2)
Fill a Rounded Rectangle g.fillRoundRect(x1,y1,x2,y2)
Oval g.drawOval(x1,y1,x2,y2)
Fill an Oval g.fillOval(x1,y1,x2,y2)
Arc g.drawArc(x1,y1,x2,y2)
Fill an Arc g.fillArc(x1,y1,x2,y2)
Copy an Area CopyArea(x1,y1,x2,y2)
Clear an Area ClearArea(x1,y1,x2,y2)
   

Top of Page


 

15 Fonts and Drawing Text

public void paint(Graphics g) 
{ 
    Font f = new Font("TimesRoman",Font.Plain,18);  
    g.setFont(f); 
    g.drawstring("Hello My string "); 
}

 

Function Arguments Type returned
     
.setFont object  
.setName    
.setSize    
.setStyle    
     
.getFont    
.getName    
.getSize    
.getStyle    
     
isBold   boolean
isPlain   boolean
isitalic   boolean
     

 

Font Methods

     
stringWidth Width of a string  
charWidth Width of a character  
getAscent Ascent of character  
getDecent Decent of character  
getLeading Leading between characters  
getHeight Height of character  
     

 

Top of Page


16 Colour

Color c=new Color(R1,G1,B1); 
R1=0 to 255 Red  
G1=0 to 255 Green 
B1=0 to 255 Blue

Red 255,0,0
Green 0,255,0
Blue 0,0,255
Pink 255,175,175
Orange 255,200,0
Light Gray 192,192,192
Gray 128,128,128
Dark Gray 64,64,64
Black 0,0,0

 

g.setColor(new Color(R1,G1,B1)); 
g.setColor(Color.Gray);

Top of Page


17 Get Input From Users

System.in.read();

18 Send Output to User

System.out.println(String)

19 Man Machine Dialog

StringBuffer stBf = new stringBuffer;
Char ch;
String st;
try
{
    st=’’;
    while ((ch=(char) System.in.read()) !=’\n’)
    {
        System.out.println(ch);
        st=st+ch;
    }
}

catch(Exception e)
{
    System.out.println("Error : " +e.toString());
}

Top of Page


20 Creating Classes

Classes are ADT’s (Abstract Data Types) which combine both Variables(Attributes) and Functions (Methods)

A Class is a blueprint defining an object Defining its Attributes(Variables) and Its Methods(Functions)

An Object is an instance of a Class and is a bundle (in memory) consisting of Variables and Methods.

Objects interact with eachother using Messages
Events are raised by Methods and are handled by Methods

Objects have State ( stored in its Attributes/Variables)
Objects have Behaviour (defined in its Methods)

 

Member Variables

Provide the state of the Class and its objects.
Are declared in the body of the Class and not in member Methods
It is a standard practice to declare Member variables first

Two types of Member Variables (Attributes )

  1. Class Variables
  2. Instance Variables

Class Variables
They are shared by all Object instances of the Class
Only the Classes Objects can assess them
Are declared as Static each ocupying a single location in memory

static int myValue;

Instance Variables
Each Object has its own copy of the instance variables 
If declared as Private the Instance Variables can only be accessed by member methods of the same Object instance

Methods


Two types of Methods

  1. Class Methods
  2. Instance Methods

Class Methods
Are shared by all object instances of the Class
Each Class method occupies a single memory location
They are declared as Static

static int myMethod( )

Instance Methods
Each Object instance has its own copy of instance methods
If declared as Private these methods can only be accessed by member methods of the same Object instance

The Constructor
This method is called as the object instance is being created
It allways has the same name as the Class
It is allways declared as a Void method

The Finalize Method
This method is like the C++ Destructor However you cant predict when it will be called
This method is called just before Garbage collection.
Since garbage collection has a low priority therefore you have no guarantee when the finalize method will be called
This method is even optional

Public class myClass
{
    // Attributes


    // Class Variables
    static type VariableName;

    // Instance Variables
    type VarName;

    // Methods


    //Class Method
    static type MethodName( )
    {
// Some code here
    }
    //Instance Method

    type myClass( ) // constructor
    {
// Some code here
    }

    type MethName( )
    {

    }

}

 

Method Signatures(Method Overloading)

Each Method has a unique signature made up of the following elements:

  1. Return_Type
  2. Method_Name
  3. Method_Parameters

Return_Type Method_Name(Method_Parameters);
Thus you can have more than one method with the same name making the method an Over-loaded Method
By overloading methods you can give a method different meanings

int Plus (int x, int y)
double Plus(double x, double y)
String Plus(Sring a, String b)

In this example me have overloaded the method Plus as it has three ‘similar’ methods with different signatures

Calling a Method
Since we have declared methods in our classes we may want to use/call them
Remember methods are not accesable on their own but as object instance members
This means we need to make reference of the Object as well as the Method refer to example below

MyClass MyObjectInstanceOfMyClass = new MyClass(Its_Parameters_here);

Int i;

i= MyObjectInstanceOfMyClass.MyMemberMethodOfMyClass;

 

Parameter List of Members
This is part of the Methods signature 
It is the part of the Method where we define what types of values the method will receive
As well as assigning variables to accept the values to be passed to the method
Method(type1 paramerterName1, type2 paramerterName2, type3 paramerterName3, ……etc)

Passing Values and Objects to methods

Pass by Value
This is the default way of passing values to a method
When the types are primitive variables values are passed to the method
Local copies are made of the values from variables passed to the method this means the method can not change the values in the Variables whose value is passed to the method

Pass by Reference
When you pass an object to a method you are merery passing a reference to the Object
The method has full control of the Objects Variables (Attributes) and caution should be excercized here
Since Arrays and Strings are Objects caution should be excercized when passing them to methods

Sphere globe=new Sphere(10,10,1,1);
Obj.change(globe) // passing object globe to method

Coding the Class


Class myClass
{
    //Attributes (Internal Variables used by the Class object)
    int attribute1;
    char myCharAttribute2;
    String myStringAttribute
    // Methods (These are the Functions in the class
    void myClass( ) // This method is known as the Constructor  
    {

// it is always executed first as the object instance is made

        some_Code_here_ ;
    }

    void myMethod1( ) // This is one of many methods you add to your class
    {
        some_Code_here_ ;
    }

    int herMethod2( int myVar, char hisVar) // another method
    {
        some_Code_here_ ;
    }
}


The THIS pointer

This is a feature of Java/C++ that   you can use to access variables and methods of the current instance of an object
When a methods Attributes contains a variable of the same name as that of an Attribute
You cant access the attribute unless you use the This pointer.

Method(AttributeName)
{
    this. AttributeName= AttributeName;
}

If you want to refer to the current object to access variables of the current instance of that object use the this. Keyword

B=this.myMethod( )
This.myAttribute=21;

 


Method and Variable Access Control (Modifiers)

 

Modifier Desctiption
   
public Used to make methods/Attributes universally accessable
private To restrict methods/attributes to be only accessible inside the class
protected To restrict methods/attributes to be only accessible to the classes that are subclasses of current class
package Is implied when no modifier is used infront of variable or method

This is used to hide the name of method or attribute.

It is the default level of protection

 

public class myClass( )
{
    // Attributes
   public int myInt;
    private String herString;

    // Methods
   protected void myFunction( )
    {

    }

    public int herMethod( )
    {

    }

    int yourMethod( ) // Package
    {

    }

}

 

Creating New Objects 

You use new with the name of the class you want to create an instance of. 
String str=new String( ); 
Random rnd=new Random( );

 

Creating Array Objects (Arrays are Objects )  
String [] names = new String[30]; 
int [] itemsPurchased = new int[30];

Multidimentional Arrays 
int coords [][] = new int[12][15];

 

Date Programs 
Date d1,d2;  
d1= new Date( ); 
.d2=new Date(2000,12,31,15,45);

 

Calling Methods 

String str ="Hello there new world"; 
System.out.println(str.substring(2,6); // from char 2 to 6 
System.out.println(str.indexOf(‘n’)); // index of String where ‘n’ is first found  
System.out.println(str.toUpperCase( ) ); // string converted to upper case

 

Top of Page


21 Casting and Converting Objects and Primitive types

(typename) object

Primitive types 
(typename) value 
(typename) expression 
a= (int) (x/y);  
netPrice= (int) Price;

Casting Objects 
GreenApple a;  
Apple a2;  
a=new GreenApple; // a is an Apple object 
a2= (Apple) GreenApple //a2 is an Apply object made from a GreenApple

 

Top of Page


22 Applets and Applications

Applets

Are downloaded from the World Wide Web vis your browser  
And run in the browsers Virtual Machine

 

Applications  

Are written in the java language and don’t require browser to run they can run on many platforms .  
When writing applications you will have a class with the name of your application. Its is a good practice to name your file with the same name and .java as the file extension

Your class should include a main method

class myAccount  
{ 
    private String myAccountName; 
    private String myAccountNumber; 
    private double myBalance;

    public myAccount(String name,String number) //constructor 
   {  
        some_Code_here_ ; 
    }

    public static void main(String args[]) // Main method 
    { 
        some_Code_here_ ; 
    }

}

 

Compiling your Class file (Both Applets & Applications)
To compile your java file . For Windows95/98 /2000 / NT 
You run a program javac.exe and pass the java file name to it  
javac myJavaApplication.java

Running your application 
For Windows95/98 /2000 / NT 
You run a program java.exe and pass the class file name to it in the command line on the DOS Prompt  
java myJavaApplication.class

Running an Applet 
Applets are bundled with HTML documents and are launched from the browser by opening the HTML document

 

Top of Page


23 APPLETS

Creating Applets 
Applets have more activities corresponding to major events to address than applications

APPLET MAIN METHODS

Initialization
public void init( )

When an applet is first loaded this method is called during creation of initial object instance to set the initial state of the object

Starting
public void start( ) 
After Initialization, or after stopping and starting this method is called

Stopping
public void stop( ) 
On stopping this method is called 
Stopping and starting go hand in hand.  
Stopping occurs when the user leaves the page containing the current applet or when you call stop( )

Destroying
public void destroy( ) 
This method is called by the applet to cleanup before it is freed or the browser exits

 

To launch an Applet (HTML TAGs) 

<APPLET CODE="myapplet.class" "ARCHIVE=myFile.jar" WIDTH=50 HEIGHT=20>  
</APPLET>

 

Creating a Sub Classes in your applets  

All applets are sub classes of the Applet Class 
A sub class of Applet inherits the behavior from this class

public class myApplet extends java.applet.Applet 
{ 
   import java.awt.Graphics; 
   import java.awt.Font; 
   import java.awt.Color

    Font f=new Font(TimesRoman",Font.Bold,36); 
   public void paint(Graphics g) 
   { 
        g.setFont(f); 
        g.setColor(Color.red);  
   g.drawString("Hello world",5,50); 
   }

}

Top of Page


24 Source Files

  • The Extension .java
  • Must contain a public class

 

Example of a Package

Package Geometry;  
// imports  
import java.awt.Graphics 
// Class Definition/s 
public class Line 
{ 
    // Attributes 
    ………. Etc 
    // Methods 
    ……..…etc 
}

Top of Page


25 Wrapper Classes

Can be used as object variations of primitive data types

Primitive Data type Wrapper Class
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double

 

Top of Page


26 Low-Level System-Access Classes

The System and Runtime classes offer access to system information and resources

 

The System Class
You don’t need to instantiate an object from the System Class.
The System class encaptulates the standard input and standard output and error output streams

I=System.in.read( );

System.out.println("I="+I);

Str=e.toString( );

System.out.println("Error="+ str);

 

The Runtime Class

Offers access to the runtime environment

  1. Available System Memory
  2. Memory Usage
  3. Platform specific Program Launching

FreeMemory=rt.freeMemory; // Bytes

TotalMemory=rt.totalMemory; // Bytes

Top of Page


27 Extending Classes

Inheritance

You can derive Sub Classes from a Base Class or Super Class

They will inherit both methods and attributes

Mamals

Primates Rodents Carnivores (Super class)

Cats Dogs (derived Classes)

 

 

Inherited Data members

Access Modifier Access from sub class in same package Access from sub class
No Access Modifier( equivalent to a C++ friend function) Yes No
Public Yes Yes
Private No No
Protected Yes Yes

 

Top of Page


28 Poly Morphasis

Related to method overiding

Enables different subclasses to implement the same method differently

 

Method Overioding

A method in a Base class and the same one in a sub class can have identical (signature) parameters

Overiding methods in sub classes will replace the same method in the super class

Overriding method must be defined in the sub class

 

 

Java.lang.Object (Universal super Class)

MyClass1 Myclass2

clone() Makes identical copy of a class
equal()  
getclass() Returns the object class
toString() Returns a character representation of the object id
finalize() Object destructor

 

Object reference

Is stored as a 32bit address pointing to the object

 

Top of Page


29 Object Casting Rules

Implicid Casting

Casting a super class object from a sub class object

 

Explicit Casting

Casting a sub class object from a super class object

Not allowed

You cant cast another sub class object from a object that is also a sub class from the same super class

 

 

Top of Page


30 Abstract Classes

One or more methods will be defined

One or more methods will Not be declared

You cnat instantiate an abstract class

You must create sub classes to instanciate objects

use the key word abstract for class abstract methods

Public abstract class myclass

{

public abstract void sound();

public abstract void affection();

}

 

Top of Page


31 Final Classes

Can not be sub classed

Public final class Lion

{

 

}

"Like variables Final denotes Const in VB"

 

Top of Page


32 Interfaces

A device for unrelated objects to interface with each other.

Public interface interfaceName

{

}

class myClass implements interfacename,interface2,interface3………etc

{

 

}

An interface is a total abstraction it has no implimentation

This is Java’s way of implementing "multiple inheritance"

 

Top of Page


Index

Chapter Content
23 #APPLETS
22 #Applets and Applications
8 #ARRAYS
6 #Assignment
7 #Branches and Loops
21 #Casting and Converting Objects and Primitive types
10 #Casting and Converting Objects and primitive types
16 #Colour
4 #Comparison operators
20 #Creating Classes
2 #Escape Codes
15 #Fonts and Drawing Text
9 #Formated Printing (Floating Point)
17 #Get Input From Users
14 #Graphics
1 #Literals
5 #Logical operators
19 #Man Machine Dialog
11 #Math Class
  3 #Primitive Data Types
18 #Send Output to User
24 #Source Files
12 #String Class Functions
13 #StringBuffer Class Functions
Contents
Samples Sample Applications and Applets
Feedback Tell Nico What you think of his Java Page

Top of Page


Sample Applications and Applets

 

Number Description
S1 Fuel Consumption Calculator
S2 Student Symbol
S3 StudentMarks

S1   Fuel Consumption Calculator

class fuelConsumption
{
    //Attributes
    private double litres;
    private double kilometers;
    private double Rate;
    public String sRegistration;
    public String sModel;

    //Methods
    public fuelConsumption(String model,String registration)//constructor
    {
        litres=0.0;
        kilometers=0.0;
        Rate=0.0;
        sModel=model;
        sRegistration=registration;
    }
    public void setLitres(double l)
    {
        litres=l;
    }

    public void setKilometers(double k)
    {
        kilometers=k;
    }

    public double getLitres( )
    {
        return litres;
    }

    public double getKilometers( )
    {
        return kilometers;
    }

    public double getRate( )
    {
        return Rate;
    }

    private void calculateRate( )
    {
        Rate=100.0 * litres / kilometers;        
    }

    public static void main(String args[])
    {
        fuelConsumption fcalc = new fuelConsumption("Hyundai Elantra","KFK612GP");

        fcalc.setLitres(52.34);
        fcalc.setKilometers(712.72);
        fcalc.calculateRate();
        System.out.println("Consumption for " +fcalc.sModel + " " + fcalc.sRegistration);
        System.out.println("Litres= " + fcalc.getLitres());
        System.out.println("kilometers= " + fcalc.getKilometers());
        System.out.println("Consumption Rate = " + fcalc.getRate() + "litres/100Km");
    }

}

Top of Page


S2 Student Symbol

class studentSymbol
{
    //Attributes
    private double Rate;
    public double studentMarks;
    public String studentName;
    public String studentSymbol;

    //Methods
    public studentSymbol(String student,double marks)//constructor
    {
        studentMarks=marks;
        studentName=student;
    }

    public void symbol(double marks)
    {
       
        if (marks>79)
                studentSymbol="A";    
        else if (marks>69)        
                studentSymbol="B";    
        else if (marks>59)
                studentSymbol="C";    
        else if (marks>49)
                studentSymbol="D";    
        else if (marks>39)
                studentSymbol="E";    
        else   
                studentSymbol="F";
       
    }


    public static void main(String args[])
    {
        int i,j;
       

        studentSymbol marks = new studentSymbol("John Doe",82.12);

        System.out.println("Student : " + marks.studentName);
        System.out.println("marks : " + marks.studentMarks);
        marks.symbol(marks.studentMarks);    
        System.out.println("symbol : " + marks.studentSymbol);
        System.out.println(" ");
        System.out.println("Mark Symbol");
        for(i=10;i<100;i+=10)
        {
            marks.symbol(i);
            System.out.println(i+" "+marks.studentSymbol);   
        }
    }

}

Top of Page


S3 StudentMarks

class StudentMarks

{

        public String getSymbol(double marks)

        {

                String symbol;

                int mks; mks=(int) marks/10;

                symbol="F";

                switch (mks)

                {

                    case 10:

                    case 9:

                    case 8:

                            symbol="A";

                            break;

                    case 7:

                            symbol="B";

                            break;

                    case 6:

                            symbol="C";

                            break;

                    case 5:

                            symbol="D";

                            break;

                    case 4:

                            symbol="E";

                            break;

                    default:

                            symbol="F";

                            break;

                }

            return symbol;

        }

 

    public static void main(String args[])

    {

         int i;

        double marks;

        String symbol;

        StudentMarks Student= new StudentMarks( );

        for(i=0;i<12;i++)

            {

                    marks=100*Math.random( );

                    symbol=Student.getSymbol(marks);

                    System.out.println("Mark " + marks + "Symbol=" + symbol );

            }

        }

}

 

 

Top of Page


Tell Nico What you think of his Java Page

Please send mail to: [email protected]  with  comments about the content  this Java Page.

 

 

Hosted by www.Geocities.ws

1