TechAlpine – The Technology world

Test your Java skills – Series IV

Java Coding Skills

Java Coding Skills – Test your knowledge

Introduction: This is another Java tips series. We have mainly focused on the coding and implementation part. We have discussed different common Java implementations with coding examples. You can test it directly by creating your own Java code. Hope this will help you understand the basic things in core Java.







How to convert an infix expression to postfix expression?

A: Following example demonstrates how to convert an infix to postfix expression by using the concept of stack. Here push (), pop () and peek () methods are used to perform the task. And the Stack class is used to hold the expressions.

import java.io.IOException;

public class InToPost {

private Stack theStack;

private String input;

private String output = “”;

public InToPost(String in) {

input = in;

int stackSize = input.length();

theStack = new Stack(stackSize);

}

public String doTrans() {

for (int j = 0; j < input.length(); j++) {

char ch = input.charAt(j);

switch (ch) {

case ‘+’:

case ‘-‘:

gotOper(ch, 1);

break;

case ‘*’:

case ‘/’:

gotOper(ch, 2);

break;

case ‘(‘:

theStack.push(ch);

break;

case ‘)’:

gotParen(ch);

break;

default:

output = output + ch;

break;

}

}

while (!theStack.isEmpty()) {

output = output + theStack.pop();

}

System.out.println(output);

return output;

}

public void gotOper(char opThis, int prec1) {

while (!theStack.isEmpty()) {

char opTop = theStack.pop();

if (opTop == ‘(‘) {

theStack.push(opTop);

break;

}

else {

int prec2;

if (opTop == ‘+’ || opTop == ‘-‘)

prec2 = 1;

else

prec2 = 2;

if (prec2 < prec1)

{

theStack.push(opTop);

break;

} else

output = output + opTop;

}

}

theStack.push(opThis);

}

public void gotParen(char ch){

while (!theStack.isEmpty()) {

char chx = theStack.pop();

if (chx == ‘(‘)

break;

else

output = output + chx;

}

}

public static void main(String[] args) throws IOException {

String input = “1+2*4/5-7+3/6”;

String output;

InToPost theTrans = new InToPost(input);

output = theTrans.doTrans();

System.out.println(“Postfix is ” + output + ‘\n’);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

}

The above code sample will produce the following result.

124*5/+7-36/+

Postfix is 124*5/+7-36/+

How to implement Queue?

A: Following example shows how to implement a queue in an employee structure. Linked list is an implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface.The LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.

import java.util.LinkedList;

class GenQueue {

private LinkedList list = new LinkedList();

public void enqueue(E item) {

list.addLast(item);

}

public E dequeue() {

return list.poll();

}

public boolean hasItems() {

return !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

while (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

public static void main(String[] args) {

GenQueue empList;

empList = new GenQueue();

GenQueue hList;

hList = new GenQueue();

hList.enqueue(new HourlyEmployee(“T”, “D”));

hList.enqueue(new HourlyEmployee(“G”, “B”));

hList.enqueue(new HourlyEmployee(“F”, “S”));

empList.addItems(hList);

System.out.println(“The employees’ names are:”);

while (empList.hasItems()) {

Employee emp = empList.dequeue();

System.out.println(emp.firstName + ” ” + emp.lastName);

}

}

}

class Employee {

`     public String lastName;

public String firstName;

public Employee() {

}

public Employee(String last, String first) {

this.lastName = last;

this.firstName = first;

}

public String toString() {

return firstName + ” ” + lastName;

}

}

class HourlyEmployee extends Employee {

public double hourlyRate;

public HourlyEmployee(String last, String first) {

super(last, first);

}

}

The above code sample will produce the following result.

The employees’ names are:

T D

G B

F S

How to reverse a string using stack?

A: Following example shows how to reverse a string using stack with the help of user defined method StringReverserThroughStack ().A simple Stack in Java, implemented as an object-oriented, recursive data structure, a singly linked list. Note that Java already provides a Stack class

import java.io.IOException;

public class StringReverserThroughStack {

private String input;

private String output;

public StringReverserThroughStack(String in) {

input = in;

}

public String doRev() {

int stackSize = input.length();

Stack theStack = new Stack(stackSize);

for (int i = 0; i < input.length(); i++) {

char ch = input.charAt(i);

theStack.push(ch);

}

output = “”;

while (!theStack.isEmpty()) {

char ch = theStack.pop();

output = output + ch;

}

return output;

}

public static void main(String[] args) throws IOException {

String input = “Java Source and Support”;

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(input);

output = theReverser.doRev();

System.out.println(“Reversed: ” + output);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

 

}

}

The above code sample will produce the following result.

JavaStringReversal

Reversed:lasreveRgnirtSavaJ







How to check whether antialiasing is enabled or not?

A: Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class. Aliasing occurs when a signal (in this case, a 2D graphics signal) is sampled and quantized from a continuous space into a discretized space. Sampling is the process of reading a value from a continuously varying signal. Quantization is the process by which these continuous sampled values are assigned a discrete value in the finite space represented by digital (binary-based) systems.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JComponent;

import javax.swing.JFrame;

public class Main {

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(true);

}

}

class MyComponent extends JComponent {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

RenderingHints rh = g2d.getRenderingHints();

boolean bl = rh.containsValue

(RenderingHints.VALUE_ANTIALIAS_ON);

System.out.println(bl);

g2.setRenderingHint(RenderingHints.

KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

}

}

The above code sample will produce the following result.

False

False

False

How to display colors in a frame?

A: Following example displays how to a display all the colors in a frame using setRGB method of image class. The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner.

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import javax.swing.JFrame;

public class Main extends JComponent {

BufferedImage image;

public void initialize() {

int width = getSize().width;

int height = getSize().height;

int[] data = new int[width * height];

int index = 0;

for (int i = 0; i < height; i++) {

int red = (i * 255) / (height – 1);

for (int j = 0; j < width; j++) {

int green = (j * 255) / (width – 1);

int blue = 128;

data[index++] = (red < < 16) | (green < < 8) | blue;

}

}

image = new BufferedImage

(width, height, BufferedImage.TYPE_INT_RGB);

image.setRGB(0, 0, width, height, data, 0, width);

}

public void paint(Graphics g) {

if (image == null)

initialize();

g.drawImage(image, 0, 0, this);

}

public static void main(String[] args) {

JFrame f = new JFrame(“Display Colours”);

f.getContentPane().add(new Main());

f.setSize(300, 300);

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

f.setVisible(true);

}

}

The above code sample will produce the following result.

Displays all the colours in a frame.








What is threading in java?

A: A Java program can contain many threads, all of which may be created without the explicit knowledge of the developer. For now, all you need to consider is that when you write a Java application, there is an initial thread that begins its operation by executing the main() method of your application. When you write a Java applet, there is a thread that is executing the callback methods (init(), actionPerformed(), etc.) of your applet; we speak of this thread as the applet’s thread. In either case, your program starts with what you can consider as a single thread. If you want to perform I/O (particularly if the I/O might block), start a timer, or do any other task in parallel with the initial thread, you must start a new thread to perform that task.

How to display text in different fonts?

A: Following example demonstrates how to display text in different fonts using setFont () method of Font class. The Font class represents fonts, which are used to render text in a visible way. A font provides the information needed to map sequences of characters to sequences of glyphs and to render sequences of glyphs on Graphics and Component objects.

import java.awt.*;

import java.awt.event.*

import javax.swing.*

public class Main extends JPanel {

String[] type = { “Serif”,”SansSerif”};

int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,

Font.ITALIC + Font.BOLD };

String[] stylenames =

{ “Plain”, “Italic”, “Bold”, “Bold & Italic” };

public void paint(Graphics g) {

for (int f = 0; f < type.length; f++) {

for (int s = 0; s < styles.length; s++) {

Font font = new Font(type[f], styles[s], 18);

g.setFont(font);

String name = type[f] + ” ” + stylenames[s];

g.drawString(name, 20, (f * 4 + s + 1) * 20);

}

}

}

public static void main(String[] a) {

JFrame f = new JFrame();

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

}

);

f.setContentPane(new Main());

f.setSize(400,400);

f.setVisible(true);

}

}

The above code sample will produce the following result.

Different font names are displayed in a frame.

How to draw a line using GUI?

A: Following example demonstrates how to draw a line using draw() method of Graphics2D class with Line2D object as an argument. The setPaint () method of the Graphics2D class has been used to paint the line. Here java applet is used to display the line on a JFrame.

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

import javax.swing.JFrame;

public class Main extends JApplet {

public void init() {

setBackground(Color.white);

setForeground(Color.white);

}

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setPaint(Color.gray);

int x = 5;

int y = 7;

g2.draw(new Line2D.Double(x, y, 200, 200));

g2.drawString(“Line”, x, 250);

}

public static void main(String s[]) {

JFrame f = new JFrame(“Line”);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

JApplet applet = new Main();

f.getContentPane().add(“Center”, applet);

applet.init();

f.pack();

f.setSize(new Dimension(300, 300));

f.setVisible(true);

}

}

The above code sample will produce the following result.

Line is displayed in a frame.

How to display a message in a new frame?

A: Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this on the frame. Here Graphics2D and Rectangle2D classes have been ued to make the initial component.  And then the message is displayed on a JPanel component.

import java.awt.*;

import java.awt.font.FontRenderContext;

import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setFont(new Font(“Serif”, Font.PLAIN, 48));

paintHorizontallyCenteredText(g2, “Java Source”, 200, 75);

paintHorizontallyCenteredText(g2, “and”, 200, 125);

paintHorizontallyCenteredText(g2, “Support”, 200, 175);

}

protected void paintHorizontallyCenteredText(Graphics2D g2,

String s, float centerX, float baselineY) {

FontRenderContext frc = g2.getFontRenderContext();

Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);

float width = (float) bounds.getWidth();

g2.drawString(s, centerX – width / 2, baselineY);

}

public static void main(String[] args) {

JFrame f = new JFrame();

f.getContentPane().add(new Main());

f.setSize(450, 350);

f.setVisible(true);

}

}

The above code sample will produce the following result.

JAVA and J2EE displayed in a new Frame.







How to display a pie chart using a frame?

A: Following example displays how to a display a piechart by making Slices class & creating arc depending on the slices. In this example AWT and swing components are used to draw the chart. Arguments are passed to the drawPie () method from the main () method. And the completed chart is displayed on a JFrame.

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

import javax.swing.JFrame;

class Slice {

double value;

Color color;

public Slice(double value, Color color) {

this.value = value;

this.color = color;

}

}

class MyComponent extends JComponent {

Slice[] slices = { new Slice(5, Color.black),

new Slice(33, Color.green),

new Slice(20, Color.yellow), new Slice(15, Color.red) };

MyComponent() {}

public void paint(Graphics g) {

drawPie((Graphics2D) g, getBounds(), slices);

}

void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {

double total = 0.0D;

for (int i = 0; i < slices.length; i++) {

total += slices[i].value;

}

double curValue = 0.0D;

int startAngle = 0;

for (int i = 0; i < slices.length; i++) {

startAngle = (int) (curValue * 360 / total);

int arcAngle = (int) (slices[i].value * 360 / total);

g.setColor(slices[i].color);

g.fillArc(area.x, area.y, area.width, area.height,

startAngle, arcAngle);

curValue += slices[i].value;

}

}

}

public class Main {

public static void main(String[] argv) {

JFrame frame = new JFrame();

frame.getContentPane().add(new MyComponent());

frame.setSize(300, 200);

frame.setVisible(true);

}

}

The above code sample will produce the following result.

Displays a piechart on a frame.

 

Please follow and like us:
0

Leave a Reply

Your email address will not be published. Required fields are marked *


7 − 6 =

============================================= ============================================== Buy TechAlpine Books on Amazon
============================================== ----------------------------------------------------------------

Enjoy this blog? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+
http://techalpine.com/test-your-java-skills-series-iv">
LinkedIn