ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 29

Updated on October 16, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Lesson 29: Java classes and methods

In Lesson 28, we learnt how to create Java constructors and setter methods. We saw how we can use constructors to set default values and how we can use setter methods to assign new values that overwrite the default values.

In this lesson, we shall continue from where we left in Lesson 28 and learn more on what we can do with Java classes. For you to understand the concepts used in this particular lesson, I recommend that you revisit Lesson 27 and Lesson 28.

We are going to add three more methods in the Examination class. Each of these methods will perform a specific function.

One method will return the Examination name another will return the score while the last method will return the grade.

We shall also use control structures such as IF ... ELSE statements to add functionality to these methods. Remember the final code we had in the class ExamDetails? Here, have a look at it again:

Still in the ExamDetails class we are going to add another method that will return the Examination name. The method will receive a two characters input and use IF … ELSE statement to return the full examination name. For example if we pass “VB” the method should return “Visual Basic .NET”. Add the following code in the ExamDetails class. You can either type or copy and paste the code.

Java classes and methods

package examination;

public class ExamDetails {
    private String Student_name;
    private String Exam_name;
    private String Exam_score;
    private String Exam_grade;
    
    ExamDetails(){
       Student_name = "No name given";
       Exam_name = "unknown";
       Exam_score = "No score";
       Exam_grade = "No grade";
    }
    String StudentName(String Sname){
       Student_name = Sname;
       return Student_name;
    }
    String ExamName(String Ecode){
        //Return examination name according to code passed
        if(Ecode.equals("VB")){
            Exam_name = "Visual Basic .NET";
        
        }else if(Ecode.equals("JV")){
            Exam_name = "Java .NET";   
        
        }else if(Ecode.equals("PH")){
            Exam_name = "PHP";
        
        }else{
            Exam_name = "No Exam selected"; //Incase no code was entered
        }
        return Exam_name;
    }
}

In the above code, the method ExamName receives a two characters input representing the examination name.

Using IF … ELSE statement, it returns the full examination name representing the two characters input else it returns the string "No Exam selected".

In the Examination class i.e. the main class, add the code to pass the Examination two characters input (Ecode) and the output statement like shown below:

At this stage, run the main class again and this time you expect it to display the Student name and Examination name.

Just like what we have done with the ExamName method, we are going to add another method that will return the examination score. Add the following code in the ExamDetails class.

Java classes and methods

package examination;

public class ExamDetails {
    private String Student_name;
    private String Exam_name;
    private String Exam_score;
    private String Exam_grade;
    
    ExamDetails(){
       Student_name = "No name given";
       Exam_name = "unknown";
       Exam_score = "No score";
       Exam_grade = "No grade";
    }
    String StudentName(String Sname){
       Student_name = Sname;
       return Student_name;
    }
    String ExamName(String Ecode){
        //Return examination name according to code passed
        if(Ecode.equals("VB")){
            Exam_name = "Visual Basic .NET";
        
        }else if(Ecode.equals("JV")){
            Exam_name = "Java .NET";   
        
        }else if(Ecode.equals("PH")){
            Exam_name = "PHP";
        
        }else{
            Exam_name = "No Exam selected"; //Incase no code was entered
        }
        return Exam_name;
    }
    String ExamScore(int Escore){
        Exam_score = "Score: "+Escore + "%"; //Get score
        return Exam_score;
    }
}

The ExamScore method combines the score with strings “Score:“ and “%”. So if the value in Escore is 67, the text "Score: 67%" will be stored in the Exam_score field. In the Examination class i.e. the main class, add the code to pass the score (Escore) and the output statement like shown below. Run the program again to see the output.

Now for the final part, we are going to add another method that will return the examination grade according to the score attained. Add the following code in the ExamDetails class.

Java classes and methods

package examination;

public class ExamDetails {
    private String Student_name;
    private String Exam_name;
    private String Exam_score;
    private String Exam_grade;
    
    ExamDetails(){
       Student_name = "No name given";
       Exam_name = "unknown";
       Exam_score = "No score";
       Exam_grade = "No grade";
    }
    String StudentName(String Sname){
       Student_name = Sname;
       return Student_name;
    }
    String ExamName(String Ecode){
        //Return examination name according to code passed
        if(Ecode.equals("VB")){
            Exam_name = "Visual Basic .NET";
        
        }else if(Ecode.equals("JV")){
            Exam_name = "Java .NET";   
        
        }else if(Ecode.equals("PH")){
            Exam_name = "PHP";
        
        }else{
            Exam_name = "No Exam selected"; //Incase no code was entered
        }
        return Exam_name;
    }
    String ExamScore(int Escore){
        Exam_score = "Score: "+Escore + "%"; //Get score
        return Exam_score;
    }

    //Here we find grade
    String ExamGrade(int Escore){
        String grade = "";   
        if(Escore >=0 && Escore <= 35){
            grade = "FAIL";

        }else  if(Escore >=35 && Escore <= 50){
            grade = "PASS";

        }else  if(Escore >=50 && Escore <= 70){
            grade = "CREDIT";

        }else  if(Escore >=70 && Escore <= 100){
            grade = "DISTINCTION";

        }else{
            grade = "Score out of range";

        }
        return "Grade: "+grade;
    }
}

In the main class, add the code to pass the score and output the grade just like we did with the other methods. The complete main class i.e. Examination class should look like shown below. Run the main class and you should be able to get the Student name, Examination name, Score and Grade.

Sample Java problem with copy and paste solution code

Write a Java application which meets the following requirements:

In the application, you should declare a class called “Employee” with the following details:

Variables

Variable Name
Description of variable
EmpNo
Employee Number
EName
Employee Name
EDesig
Employee Designation
BSal
Basic Salary
HA
House Allowance

Methods

Member Functions
Description of Member Functions
getValues()
Should initialize the values for the member variables EmpNo, ENname, EDesig, BSal, HA
CalculateSalary()
Should calculate the Gross salary as the sum of the BSal and HA
DisplayValues()
Should print the value of the instance variables along with Gross salary

Requirements

  1. In your main method, create N number of Employee objects, where the value of N is obtained from the user and store the objects into an array.
  2. Use appropriate methods to read the values of the Employee objects from user, Calculate the Gross Salary for each Employee and print employee details and salary details of all objects created.
  3. Use exception handling appropriately.
  4. Use comments to illustrate the various concepts applied / utilized in the solution.
  5. Ensure the use of meaningful variable names, consistent indentation of program code


Java solution code for the above problem

/*
 * This program accepts salary details
 * of N number of employees, calculates gross salary
 * and print the final details on the console
 */
package employee;
import javax.swing.JOptionPane;
public class Employee {
    private int EmpNo; //Employee Number
    private String EName; //Employee name
    private String EDesig; //Employee designation
    private int BSal; //Basic salay
    private int HA; //House allowance
    private int GSal; //Gross salary
    
    Employee() { //Create Employee class constructor and set default values
        EmpNo = 0; 
        EName = "Unknown"; 
        EDesig = "Unknown";
        BSal = 0; 
        HA = 0; 
        GSal = 0;
}
  
   void getValues(){ //Initialize instance variables 
        EmpNo = Integer.parseInt(JOptionPane.showInputDialog("Enter employee number"));
        EName = JOptionPane.showInputDialog("Enter employee name");
        EDesig = JOptionPane.showInputDialog("Enter designation");
        BSal = Integer.parseInt(JOptionPane.showInputDialog("Enter basic salary"));
        HA = Integer.parseInt(JOptionPane.showInputDialog("Enter House allowance"));
    }
   int CalculateSalary(){ //Calculate basic salary
       GSal = BSal+HA;
       return GSal;
   }
   void DisplayValues(){ //Print values of the instance variables
       
       System.out.println("Employee nunber: "+EmpNo);
       System.out.println("Employee name: "+EName);
       System.out.println("Designation: "+EDesig);
       System.out.println("Basic salary: "+BSal);
       System.out.println("House allowance: "+HA);
       System.out.println("Gross salary: "+this.CalculateSalary());
   }
    public static void main(String[] args) {
      //Get N number of employees from the user
      int EmpNum = Integer.parseInt(JOptionPane.showInputDialog("Calculate salary for how many employees?"));
      Employee[] newEmp = new Employee[EmpNum];//Create array of N objects
      
      try { //Trap and handle errors if any
            for(int i = 0; i<newEmp.length; i++){
                 newEmp[i] = new Employee(); //Loop through the objects and for 
                 newEmp[i].getValues(); //every object, get employee details 
      }
      System.out.println("----------------------------------------------");
      System.out.println("EMPLOYEES SALARY DETAILS. TOTAL EMPLOYEES: "+EmpNum);
      
            for(int i = 0; i<newEmp.length; i++){
                System.out.println("----------------------------------------------");
                newEmp[i].DisplayValues(); //Loop through the objects and print details
            }
      }catch (Exception err ) {
            System.out.println(err.getMessage());//Throw error message if any
        }
     }
  }

Here is a Java problem for you to try

A parking garage charges $10 minimum fee to park for up to three hours. The garage charges an additional $2 per hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $50. Assume that no car parks for longer than 24 hours at a time.

Write a Java application that calculates and displays the parking charges for each customer who parked in the garage the previous day. You should enter in a dialog box the hours parked for each customer. The program calculates and displays the running total of previous day’s receipts. The program should use the method calculateCharges() to determine the charge for each customer.

Well, that is all we have for Java classes but I would recommend that you practice more and look for more resources about Java classes and methods. Learn how to write more advanced Java classes and how to manipulate Java classes and methods. In the next lesson, we shall look at Java and Inheritance.

<< Lesson 28 | Lesson 30 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi Paul,

      Welcome and thanks for the visit and comment.

    • profile image

      paul bernard 

      7 years ago

      u are awesome dude!! god bless u!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi Nell Rose,

      Thanks for that compliment and thanks for the visit and vote.

    • Nell Rose profile image

      Nell Rose 

      7 years ago from England

      This I am sure is going to be so helpful to people who need this info, great work and voted up!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi kashmir56,

      The other fact about programming is that we use programmed devices everyday..iPhone, Computer, ATM, Tablets...so i would say programming is truly part of our life. Thanks for the visit and comment.

    • kashmir56 profile image

      Thomas Silvia 

      7 years ago from Massachusetts

      Hi my friend, has i said before i know very little about programming, but this will be very helpful for those who may be just learning it. Well done !

      Vote up and more !!! SHARING !

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi Lord De Cross,

      I would not imagine how i would have completed my undergraduate studies if i didn't get a little push by researching on net, i guess this is my small way of paying back. Thanks for the visit and comment.

    • Lord De Cross profile image

      Joseph De Cross 

      7 years ago from New York

      Bringing the class to every corner of the world, who cannot afford a school or a teacher. Valuable indeed, and well written my friend. You are doing a favor to so many as I said before. Just keep them coming and the world will remember your effort! From machine language to C++, cyber intelligence is helping us to live better.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)