Knowledge7

The Linux and Mobile Solution Provider

  • About
  • Training
  • Services
  • Clients
  • In the news
  • Blog
  • Contact Us
You are here: Home / Blog

String Manipulation and Collections

This topic is part of our Object-Oriented Programming in Java training

Strings

In Java, Strings are immutable i.e. cannot be changed and this explains why there exists other kinds of strings in the language, namely StringBuffers (since the beginning) and StringBuilders (since Java 5.0).

The best way to understand the syntax and semantics of strings in Java is to write progressively more complex programs. The work to do is:

  • Write a Java program which reads a sentence and a number of repetitions from standard input. The program should then create a string which is the sentence repeated the specified number of times. The string should then be displayed on standard output.
  • Write a Java program which reads words from the system dictionary and finds all the words with start with “aba”. Those words followed by their capitalized versions are printed. In Unix, the system dictionary is a normal text file at /usr/share/dict/words
  • Write a Java program which reads words from the system dictionary and finds and print all the words with match with a regular expression entered by the user.

Collections

Java has a rich class library containing two very important kinds of collections: Lists and Maps. Lists are linear structures which can contain several elements. Typical lists include ArrayLists and LinkedLists. Maps are what are known as associative arrays in other programming languages and, when used properly, give the programmer a lot of power and flexibility. In order to master Lists and Maps, it is important to write actual Java applications. The work to do is:

  • Write a Java program that prompts the user for marks obtained by students for one exam and displays on screen the best mark and the average mark.
  • Write a Java program that prompts the user for words and displays for each unique word the number of times it was typed.
  • Write a program which finds all anagrams from the system dictionary. Two distinct words are anagrams if they contain the same letters.

Do not forget to refer to the Java API Specification when needed.

This topic is part of our Object-Oriented Programming in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Fundamentals of Java and Input/Output

This topic is part of our Object-Oriented Programming in Java training

Java is a platform. It consists of:

  • a virtual machine capable of running bytecodes
  • a compiler which transforms Java code into bytecodes
  • a programming language
  • a standard library

The virtual machine, the compiler as well as the various components of the standard library have been released as open-source software by Sun (now owned by Oracle) and, consequently, the Java platform is well supported on all computer platforms. Forks of Sun’s original Java include OpenJDK.

Java was designed by James Gosling in 1995 to power embedded devices and, in 2012, Java powers Android smartphones and tablets and Blu-Ray drives for example. Java has also proved to be very successful in enterprises. Applications written in Java and conforming to the Java Enterprise Edition set of specifications are found in most of the large companies.

Setting up the development environment

  • Make sure Java is installed
  • Install the IntelliJ IDEA Community Edition IDE
  • Write a Java program that displays the string of characters “Hello World” on standard output

Like Java, Eclipse is an open-source software (originally done by IBM) and, since then, has become a very important integrated development environment for Java and Android. Other IDEs used to do Java development are Netbeans and Eclipse.

Developing applications

Java is an imperative programming language, supports object-oriented programming and has a C-like syntax. The best way to learn how to program in Java is to develop progressively more complex applications. The work to do is:

  • Write a Java program that displays a multiplication table for a specific number on the standard output.
  • Write a Java program that calculates and displays the factorial of a specific number using both the recursive and iterative algorithms. When this is done, enhance the iterative version to work with big numbers.
  • Write a Java program which uses the algorithm devised by Eratosthene to display all the prime numbers which are less or equal to a specific maximum number.

Input / Output

Computer applications generally read data from input devices (e.g. the keyboard), process the data in some way and display results on output devices (e.g. a screen)

  • Write a Java program which reads integers from standard input and print out their sum on standard output. The program should read integers until the string “END” is encountered.
  • Write a Java program that prompts the user for a number of seconds (an offset), displays the current date and time and also the date and time after that offset.

In order to write those programs, it is important to understand how Input / Output is done in Java as well as how the platform handles times and dates. The relevant information is found in the Java API Specification.

This topic is part of our Object-Oriented Programming in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Extending servlets with Java Database Connectivity (JDBC)

This topic is part of our Web Application Development in Java training

The next web application we will create will allow us to look for the phone number of someone given his name:

Clicking on the Search! should display the phone number of the person if the name exists and an appropriate error message if not.

We are going to use an HMTL form and a servlet for the searching for the phone number. The new aspect is that we are going to store the names and numbers in a database in a table similar to this:

CREATE TABLE phonebook (
  name varchar(255) NOT NULL,
  number varchar(255) NOT NULL,
  PRIMARY KEY (name)
);

The work to do is to create an appropriate database, create such a table in it and populate that table with some test data.

Then, write a Java web application in which a servlet connects to and searches for phone numbers in the database. Use the Java Database Connectivity (JDBC) API. [NB: As we use MySQL, it is important to use Connector/J, the official JDBC driver for MySQL.]

Enhancing the application with proper caching

As it is now, a SQL query is issued each time someone looks for a name… even if that’s for the same name. In other words, searching for the phone number of the same person many times will systematically query the database. It would be more intelligent to query only once (the first time) and then memorise (cache) the resulting phone number.

The rationale behind this is to minimise the number of SQL queries while preserving the semantics of the application (Discuss!) i.e. increase overall performance and decrease the use of critical resources.

Drilling down

A lot of database applications are used to drill down data presented in a hierarchical manner. For instance, we may have different countries on the first level and clicking on one of the countries reveals artists from that country. Similarly, clicking on an artist reveals songs by that artist.

The objective is the build such a web application using servlet(s) and JDBC only based on the following database schema:

CREATE TABLE `countries` (
  `countryid` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY  (`countryid`)
);

CREATE TABLE `artists` (
  `artistid` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `countryid` int(11) NOT NULL,
  PRIMARY KEY  (`artistid`),
  KEY `countryid` (`countryid`)
);

CREATE TABLE `songs` (
  `songid` int(11) NOT NULL auto_increment,
  `rank` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `artistid` int(11) NOT NULL,
  PRIMARY KEY  (`songid`),
  KEY `artistid` (`artistid`)
);

ALTER TABLE `artists`
  ADD CONSTRAINT `artists_ibfk_1`
  FOREIGN KEY (`countryid`) REFERENCES `countries` (`countryid`)
  ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `songs`
  ADD CONSTRAINT `songs_ibfk_1`
  FOREIGN KEY (`artistid`) REFERENCES `artists` (`artistid`)
  ON DELETE CASCADE ON UPDATE CASCADE;

Interestingly, the application can be built either using one do-it-all servlet or using three distinct servlets (e.g. ViewCountries initially, then ViewArtists, then ViewSongs). When three such servlets are used, it is important that only one (shared) database connection is used throughout.

Back.

This topic is part of our Web Application Development in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Creating a web application using servlets

This topic is part of our Web Application Development in Java training

We will now create a non-trivial Java web application which will require the use of a servlet.

First of all, let’s create a simple HTML page containing a form to allow the user to choose a type of conversion (Rupees to Dollars / Dollars to Rupees) and the amount to convert. At this point, clicking on Go! makes no sense (but try it!)

The second step is to add a servlet to the web application which will handle the conversion. The servlet will be called with two parameters, the type of conversion and the amount, through the HTTP GET (or POST) request. [NB: We will have to add the servlet-api.jar to the web application WEB-INF/lib folder. Get the jar from Tomcat.]

The servlet will then have to get the parameters from the request, validate them and calculate a new amount based on some hard-coded conversion rate (e.g. 1 Dollar is 30 Rupees). This value should then be sent back to the browser (in an HTTP response) for display.

Export the WAR file and examine its contents. Can you see the Java servlet in it? Is it in source code form or in compiled form?

Enhancing the application

As it is, the web application uses a hard-coded conversion rate and this is artificial as, in real life, this rate changes daily. Update the web application to retrieve the conversion rate from a web service.

To make things simple, we are going to assume that the exchange rate is available at an URL similar to www.server.com/exchangerate.txt (see, web services can be simple!) And, because we are dealing with resources which are accessed through a URL, use a Java URL object during the implementation.

Back.

This topic is part of our Web Application Development in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Installing and configuring a servlet

This topic is part of our Web Application Development in Java training

For developing web applications in Java using Servlets and JSP, we will use the following software:

  • OpenJDK: an open source implementation of the Java Platform. OpenJDK is part of most Linux distributions now (as well as on Mac OS X) but needs to be manually installed on Windows.
  • Apache Tomcat: an open source software implementation of the Java Servlet and JavaServer Pages (JSP) technologies. Tomcat is a web container in which web applications written in Java can be deployed for execution.
  • SpringSource Tool Suite: a powerful variant of the open source Eclipse development environment for building Java enterprise applications. STS can be used to create web application in Java and it can also deploy those applications automatically to Tomcat. STS is made by the same people behind the Spring framework.

Installation

As mentioned above, OpenJDK is already installed in Linux. Tomcat and STS need to be installed manually.

Work to do

To check whether the whole environment is setup properly, we will create a small (but fully functional) HelloWorldWeb application using STS and deploy it to Tomcat. On execution, we expect the following:

After testing, export the project as a WAR file and examine the contents of the archive. This WAR file is what is being sent to Tomcat by STS.

This is an overview of how Tomcat works.

Back.

This topic is part of our Web Application Development in Java training

Our forthcoming training courses

  • No training courses are scheduled.

Noupei.com, a social network for people who love Mauritius

Knowledge7 is proud to announce the launching of Noupei.com, the first Mauritian social network for sharing ideas and opinions.

As we are celebrating our 44th anniversary of independence and 20th anniversary as a republic, we believe we need a platform to discuss on the various problems we have in the country as well as the possible solutions.

People can contribute ideas and comment on ideas posted by others. People can also vote for the most valuable contributions.

Noupei.com is open to all people who love Mauritius.

Our forthcoming training courses

  • No training courses are scheduled.

Give your child a head start in his university studies



Congratulations! Your child has just obtained his HSC results and you are proud that he (or she) has worked really well. Having decided to embrace a career in IT, he will start university shortly to study Computer Science.

As you want your child to have a head start in his studies, why not tell your child to learn programming?

At Knowledge7, we offer quality training courses which will give your child the knowledge and skills needed to excel at university level.

We will shortly run an Object-Oriented Programming in Java training starting on 20 March. During this training, your child will master the Java programming language, a platform used by most of the largest companies on the planet and which powers hundred of millions of mobile devices.

After this Java training, we will run an Android Application Development training course as from 8 May. During this training, your child will use his newly acquired knowledge of Java to develop Android applications as used in the latest smartphones and tablets from companies such as Samsung, Sony-Ericsson, LG, HTC, etc.

The training will finish on 5 June 2012, just in time for your child to join university and start his Computer Science classes.

We have trained people from major companies in Mauritius in the past and we are happy that the trainees left us very positive testimonials.

As a sign of encouragement to your child, we are happy to offer him 20% discount if he chooses to follow both the Java and Android training at Knowledge7. We also have free books to offer to those who register early.

Do not hesitate to contact us if you need any clarification.

Our forthcoming training courses

  • No training courses are scheduled.

My presentation on Android during Mobile Apps 2012

What is Android? How to develop apps?

View more presentations from KnowledgeSeven

Thank you for your presence during my presentation this morning at Mobile Apps 2012. I had a lot of pleasure talking about Android and how we can get the best apps for it: either using existing ones from the Android Market, subcontracting the development (to Knowledge7 for example) or by setting up an Android development team (by following our Java and Android training starting soon and getting 20% discount in the process).

I loved the questions & answers session at the end. We had great exchanges about the value of open-source software as well as competing mobile platforms.

Once again, thanks for having listened to me. I hope you learnt 1-2 interesting things.

Our forthcoming training courses

  • No training courses are scheduled.

UNIX/Linux Security Best Practices

You can take steps to protect yourself from intruders who attempt to break into your UNIX or Linux system. Among many of the different security services here are some things to do to make intrusion more difficult.

Turn off unused services

Services which you don’t enable can’t be attacked from the outside. If you don’t provide access to a service, it doesn’t matter if there is any vulnerability in the daemon which would provide that service. So disable anything you don’t need to use.

Where available, install IP filter or firewall rules

Restricting network access helps, it is no security that you won’t be attacked. But restricting access to a smaller group of systems will reduce the number of attempts you see made against you.

Install ssh and tcpd

SSH (Secure SHell) is a protocol which supports logging into a remote system or executing commands on a remote system, using an encrypted communication between the two systems. Both ssh and the tcp wrapper tcpd use a pair of configuration files to define what hosts are allowed to make connections to specific TCP services on your machine. Use these to limit access to those services and prevent unwanted intrusion attempts.

Keep your system up-to-date with the latest patches from your vendor

UNIX and Linux exploits are discovered from time to time, and if you don’t keep your configuration updated, you’ll potentially leave yourself exposed to attacks that try newly discovered vulnerabilities. Get the latest patches for your version of the OS.

UNIX File Sharing

You may want to give others access to your directory or files in one of your directories. As an individual user, you can control who has access to the files which you own, by setting UNIX file permissions. Network File System (NFS) is the most frequently used method of sharing access to a filesystem (or a directory in a filesystem) between UNIX systems.

At this point, if your system does not meet at least the above or if you need to make your Linux production systems compliant with various audit requirements, then our training should offer a good baseline and starting point, see our Linux page for more info in training and consulting services.

Our forthcoming training courses

  • No training courses are scheduled.

Learn Android and get a head start at university



You have your HSC results and you are looking forward to join university for further studies. As you want a career in IT, you have chosen to study Computer Science.

Get a head start and make things simpler later. Learn Java with us, a platform used by most of the largest companies on the planet and which powers millions of mobile devices, including 200 million Android smartphones and tablets. Join our Object-Oriented Programming in Java training course starting on 20 March.

With your new Java skills, you can then follow our Android Application Development training course.

Our forthcoming training courses

  • No training courses are scheduled.
« Previous Page
Next Page »

Looking for something?

Want to know more?

Get our newsletter

Discover the latest news, tips and tricks on Linux, the Web and Mobile technologies every week for FREE

This work is licensed by Knowledge7 under an Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license.