Array example in Java

Hope you had already gone thru Arrays in Java to get basic understanding of arrays.

Now, let us solve a simple problem using Arrays.
Arrays Problem: Write a class which has Constructor, taking marks of students as parameters. Expose methods to return max marks, min marks, avg marks, number of students scored more than 60, number of students scored less than 60.

class Student{
	private int marks[];
	
	public Student(int marks[])
	{
		this.marks=marks;
	}
	
	public int getMaxMarks()
	{
		int max = 0;
		
		for(int i=0;i < marks.length;i++)
		{
			if(marks[i] > max)
			{
				max = marks[i];
			}
		}
		
		return max;
	}
	
	public int getMinMarks()
	{
		int min = 999;
		
		for(int i=0;i < marks.length;i++)
		{
			if(marks[i] < min)
			{
				min = marks[i];
			}
		}
		
		return min;		
	}
	
	public int getAverageMarks()
	{
		int avg = 0;
		
		for(int i=0;i < marks.length;i++)
		{
			avg+=marks[i];
		}
		
		avg /= marks.length;
		
		return avg;
	}
}

public class Cond{
public static void main(String args[])
{
	int st_marks[] = {36,94,83,42,35,86,65,91};
	
	Student obj = new Student(st_marks);
	
	System.out.println("Max Marks:"+obj.getMaxMarks());
	
	System.out.println("Min Marks:"+obj.getMinMarks());
	
	System.out.println("Avg Marks:"+obj.getAverageMarks());
}
}

Note: Finding number of students scored less than 60 and more than 60 is left out, for you to work on.

Hint: To get number of students less than 60, use for loop, and in each iteration increment counter, if the mark of a student is less than 60, and return the counter value. Similarly find number of students scored greater than 60.

You may also like to read:
How to write a class in Java
Loops examples
What is purpose of Constructor

for loop examples

Hope you had already gone through loops in java to get basic understanding of loop in Java.

Below are few examples which will make you hands on, and make you aware real use of loops. First let us consider solving below problem.

For loop example problem: Take two different arrays each of size 10. Concatinate each number of first array with each number of second array, and display each combination. Hint:Output generates 100 different numbers.
Solution: First declare & initialize two array a and b. Now each number of first array need to be concatinated with each number of second array. We need two different for loops, one to iterate thru first array, another to iterate thru second array. However, these two loops need to be nested, i..e outer for loop iterates thru first array, inner for loop iterates thru second array.

public class LoopExample{
public static void main(String args[])
{
int a[] = { 23,54,89,14,83,5,29,3,93,32};
int b[] = { 21,43,26,19,3,8,25,2,8,24};

for(int i=0;i < a.length;i++)
{
for(int j=0;j < b.length;j++)
{
String tmp = a[i]+""+b[j];
System.out.println(tmp);
}
}
}
}

Also this problem can be solved using while loop or do while loops.

Another Problem: Repeat above problem, but print only the numbers which are multiples of 3.
Solution: As shown above, after the number gets created, it is in String format, to convert it to int, use Integer.parseInt() method, Further check if it is multiple of 3, using modulo operator.

public class LoopExample{
public static void main(String args[])
{
int a[] = { 23,54,89,14,83,5,29,3,93,32};
int b[] = { 21,43,26,19,3,8,25,2,8,24};

for(int i=0;i < a.length;i++)
{
for(int j=0;j < b.length;j++)
{
String tmp = a[i]+""+b[j];
int val = Integer.parseInt(tmp);
if(val%3==0)
{
System.out.println(tmp);
}
}
}
}
}

Note that each iteration does not create any entry on the Stack, but a method call creates an entry in Stack. For more details, refer what is stack memory and when an entry is added to stack memory
You may also like to read:
Core Java Interview Questions
List of Operators in java
Java Interview Questions
What are Wrapper classes
More for loop examples

What is JAR File and How to create JAR File

A JAR File, stands for Java Archive file. Like ZIP file, JAR is compressed file format, which is used to share software resources required for Java Applications. For example Hibernate, Struts, Spring,etc… provide their framework implementation through multiple JAR files. Similarly you can provide Jar files to your clients, or other Teams dependent on your Classes or packages. Even JDBC driver is provided as a Jar file. A Jar file may contain
1. bunch of .class files
2. any other resource files, like images, icons,etc… required by .class files

Also note that a jar file can have multiple packages or sub packages.

How to create JAR file in Eclipse

Below are the steps involved in creating jar file in Eclipse IDE.
1. Create a Java Project
2. Add class Files
3. Build the Project, do Testing
4. Right click on Project, and Select Export

export jar file
export jar file

5. In Export Window, select java, then JAR file, then Next button.
create-jar
create-jar

6. Now Below JAR File Specification window appears. Select various options, based on your requirement.
Select or unselect appropriate checkbox to specify if you want to Export generated class files and resources or Export Java source files and resources as well.

jar-file-specification
jar-file-specification

Browse to select a location for the JAR file, which will get created.

Select or unselect, Compress the contents of the JAR file checkbox.
Select or unselect, Overwrite existing files without warning checkbox. If you unselect this checkbox, then you will be prompted to confirm the replacement of each file that will be overwritten.

In this way you can create JAR file, out of your class files, and other required resources, and distribute it.

You may also like to read:

How to Compress and Uncompress file in Java


How to create a Jar file in a Netbeans Project?
How to create Jar file, in run time, using Java program?
How to add an external Jar file to a Eclipse Project?
How to add an external jar file to a Netbeans Project?

Complete Calculator in android

The xml code

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:paddingLeft=”10sp”
android:paddingRight=”10sp”
android:background=”@android:color/white”>
<EditText
android:layout_width=”match_parent”
android:layout_height=”80sp”
android:inputType=”textPersonName”
android:layout_marginTop=”10sp”
android:id=”@+id/t”/>

<ScrollView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/scrollView”>

<TableLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/ButtonsTable”
android:layout_marginTop=”20sp”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”>
<TableRow
android:layout_width=”wrap_content”
android:layout_height=”fill_parent”
android:gravity=”center”>

<Button
android:text=”1″
android:id=”@+id/b1″
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_width=”100sp”
android:layout_height=”wrap_content”
android:gravity=”center”/>
<Button
android:text=”2″
android:id=”@+id/b2″
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_width=”100sp”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”3″
android:id=”@+id/b3″
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_width=”100sp”
android:layout_height=”wrap_content”
android:gravity=”center”/>
</TableRow>

<TableRow
android:layout_width=”wrap_content”
android:layout_height=”fill_parent”
android:layout_marginTop=”10sp”
android:gravity=”center”>

<Button
android:text=”4″
android:id=”@+id/b4″
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>
<Button
android:text=”5″
android:id=”@+id/b5″
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”6″
android:id=”@+id/b6″
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:gravity=”center”/>
</TableRow>
<TableRow
android:layout_width=”wrap_content”
android:layout_height=”fill_parent”
android:layout_marginTop=”10sp”
android:gravity=”center”>

<Button
android:text=”7″
android:id=”@+id/b7″
android:textStyle=”bold”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:layout_height=”wrap_content”
android:gravity=”center”/>
<Button
android:text=”8″
android:id=”@+id/b8″
android:textStyle=”bold”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”9″
android:id=”@+id/b9″
android:textStyle=”bold”
android:textSize=”30sp”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:gravity=”center”/>
</TableRow>
<TableRow
android:layout_width=”wrap_content”
android:layout_height=”fill_parent”
android:layout_marginTop=”10sp”
android:gravity=”center”>

<Button
android:text=”0″
android:id=”@+id/b0″
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”/”
android:id=”@+id/bdiv”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”*”
android:id=”@+id/bmul”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>
</TableRow>
<TableRow
android:layout_width=”wrap_content”
android:layout_height=”fill_parent”
android:layout_marginTop=”10sp”
android:gravity=”center”>

<Button
android:text=”-”
android:id=”@+id/bsub”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”+”
android:id=”@+id/badd”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”.”
android:id=”@+id/bdec”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>
</TableRow>
<TableRow
android:layout_width=”wrap_content”
android:layout_height=”fill_parent”
android:layout_marginTop=”10sp”
android:gravity=”center”>

<Button
android:text=”=”
android:id=”@+id/beq”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”del”
android:id=”@+id/bdel”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>

<Button
android:text=”clr”
android:id=”@+id/bclr”
android:layout_width=”wrap_content”
android:textSize=”30sp”
android:textStyle=”bold”
android:layout_height=”wrap_content”
android:gravity=”center”/>
</TableRow>
</TableLayout>
</ScrollView>
</LinearLayout>

The java code

package com.example.CalculatorApp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyActivity extends Activity implements View.OnClickListener {

private Button b1;
private Button b2;
private Button b3;
private Button b4;
private Button b5;
private Button b6;
private Button b7;
private Button b8;
private Button b9;
private Button b0;
private Button bdiv;
private Button bmul;
private Button bsub;
private Button badd;
private Button bdec;
private Button beq;
private Button bdel;
private Button bclr;
private EditText t;
static double a = 0, b = 0, result = 0;
static int operator = 0;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t=(EditText)findViewById(R.id.t);
t.setEnabled(false);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
b3=(Button)findViewById(R.id.b3);
b4=(Button)findViewById(R.id.b4);
b5=(Button)findViewById(R.id.b5);
b6=(Button)findViewById(R.id.b6);
b7=(Button)findViewById(R.id.b7);
b8=(Button)findViewById(R.id.b8);
b9=(Button)findViewById(R.id.b9);
b0=(Button)findViewById(R.id.b0);
bdiv=(Button)findViewById(R.id.bdiv);
bmul=(Button)findViewById(R.id.bmul);
bsub=(Button)findViewById(R.id.bsub);
badd=(Button)findViewById(R.id.badd);
bdec=(Button)findViewById(R.id.bdec);
beq=(Button)findViewById(R.id.beq);
bdel=(Button)findViewById(R.id.bdel);
bclr=(Button)findViewById(R.id.bclr);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
b7.setOnClickListener(this);
b8.setOnClickListener(this);
b9.setOnClickListener(this);
b0.setOnClickListener(this);
bdiv.setOnClickListener(this);
bmul.setOnClickListener(this);
bsub.setOnClickListener(this);
badd.setOnClickListener(this);
bdec.setOnClickListener(this);
beq.setOnClickListener(this);
bdel.setOnClickListener(this);
bclr.setOnClickListener(this);
}

public void onClick(View v){
if(v.getId()==R.id.b1){
t.setText(t.getText().toString().concat(“1”));
}
if (v.getId()==R.id.b2) {
t.setText(t.getText().toString().concat(“2”));
}
if (v.getId()==R.id.b3) {
t.setText(t.getText().toString().concat(“3”));
}
if (v.getId()==R.id.b4) {
t.setText(t.getText().toString().concat(“4”));
}
if (v.getId()==R.id.b5) {
t.setText(t.getText().toString().concat(“5”));
}
if (v.getId()==R.id.b6) {
t.setText(t.getText().toString().concat(“6”));
}
if (v.getId()==R.id.b7) {
t.setText(t.getText().toString().concat(“7”));
}
if (v.getId()==R.id. b8) {
t.setText(t.getText().toString().concat(“8”));
}
if (v.getId()==R.id.b9) {
t.setText(t.getText().toString().concat(“9”));
}
if (v.getId()==R.id.b0) {
t.setText(t.getText().toString().concat(“0”));
}
if (v.getId()==R.id.bdec) {
t.setText(t.getText().toString().concat(“.”));
}
if (v.getId()==R.id.badd) {
a = Double.parseDouble(t.getText().toString());
operator = 1;
t.setText(“”);
}
if (v.getId()==R.id.bsub) {
a = Double.parseDouble(t.getText().toString());
operator = 2;
t.setText(“”);
}
if (v.getId()==R.id.bmul) {
a = Double.parseDouble(t.getText().toString());
operator = 3;
t.setText(“”);
}
if (v.getId()==R.id.bdiv) {
a = Double.parseDouble(t.getText().toString());
operator = 4;
t.setText(“”);
}
if (v.getId()==R.id.beq) {
b = Double.parseDouble(t.getText().toString());
switch (operator) {
case 1:
result = a + b;
break;

case 2:
result = a – b;
break;

case 3:
result = a * b;
break;

case 4:
result = a / b;
break;

default:
result = 0;
}
t.setText(“” + result);
}
if (v.getId()==R.id.bclr) {
t.setText(“”);
}
if (v.getId()==R.id.bdel) {
String s = t.getText().toString();
t.setText(“”);
for (int i = 0; i < s.length() – 1; i++) {
t.setText(s.charAt(i) + “”);
}
}
}
}cal

Display initial Launch Screen(Activity) in Android

Most of Android Apps display Launch Screen, when Application is being launched, for few Seconds.
To cause delay Thread.sleep() is used with 5000 milliseconds, in below code.
Below is an example of the same.

import android.app.Activity;
import android.os.Bundle;

public class LoginPage extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
}
}

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;

import java.util.Timer;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class MyActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.launch_activity);
Thread timer= new Thread()
{
public void run()
{
try
{
sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
try {
Intent i = new Intent(getBaseContext(), NewActivity.class);
startActivity(i);
finish();
}catch(Exception e){
e.printStackTrace();
}
}
}
};
timer.start();
}
}

You may also like to read:

Difference between Composition and Aggregation

In Object oriented languages, Composition, Aggregation and Inheritance are the most common relationships exist between classes.

Composition in Java

Composition is has-a relationship. Also sometimes referred as non-separable part of the whole.
Composition is more stronger relationship compared to Aggregation. Here composed object cannot exist without composing object, and both objects have same life time.

As shown in below code snippet, object of B(i..e obj) cannot exist without object of B. Object of B gets created only along with object of A. Also obj1 does not continue to exist, after object of A gets destroyed.

class A{
B obj;
//… other data members and methods, of class A
}

Aggregation

Aggregation is also a has-a relationship. Also sometimes referred as separable part to whole.
Aggregation is a weaker relationship compared to Composition.
As shown in below code snippet, object of D(i..e obj1) can exist even before object of C gets created. Also obj1 may continue to exist even after object of C is destroyed.

class C{
D obj1;
//… other data members and methods, of class C
}
Composition is Strong Has-A relationship Aggregation is a Weak Has-A relationship.

To understand difference between Composition and Aggregation, lets us take an example of a College with few Departments, and each Department with Lecturers.

aggregation and composition
aggregation and composition

Relationship between College and Department is Composition, and relationship between Department and Lecturer is Aggregation.

class College
{
  private List depts;

  public College()
  {
    depts.add(new Department("Computer Dept"));
    depts.add(new Department("Electrical Dept"));
    depts.add(new Department("Electronics Dept"));
  }

  //...other methods in College class
}

A Department cannot exist without College, hence difference between them is Strong and hence Composition.
When College no more exist, Department cannot exist.

Relationship between Department and Lecturer can be Aggregation, as it is weaker. A Lecturer can exist, even before Department exist. And Lecturer may continue to exist even after Department gets destroyed.

class Department
{
  private Lecturer my_obj;

  public void setLecturer(Lecturer lect)
  {
    my_obj = lect;
  }
  //...other methods in Department class
}

Difference between == and equals() method for a String

Result of using == and equals() method between two String objects is different.
== checks whether both String objects are referring to same address location.
equals() method checks whether the contents of both String objects are same.

public class Stringequals{

public static void main(String args[])
{
	String s1 =  new String("Hello");
	String s2 = new String("Hello");

	String str="Hello";

	String str1="Hello";

	//s2 and s3 refer to same address location
	String s3 = s2;

	if(s1==s2)//== checks address location
	{
		System.out.println("if(s1==s2)");
	}
	else
	{
		System.out.println("else (s1==s2)");
	}

	if(s2==s3)//== checks address location
	{
		System.out.println("if(s2==s3)");
	}
	else
	{
		System.out.println("else (s2==s3)");
	}

	if(s1.equals(s2))//equals checks contents of s1, s2
	{
		System.out.println("if s1 equals s2");
	}
	else
	{
		System.out.println("else s1 equals s2");
	}

	if(str==str1){
		System.out.println("if(str==str1)");
	}
}
}


Output:
else (s1==s2)
if(s2==s3)
if s1 equals s2
if(str==str1)

You may also like to read:
Inherit From String class
How to override toString() method
Difference between String and StringBuilder
String object creation with and without new

NetBeans IDE Java Quick Start Tutorial

In order to work with NetBeans IDE  , you should have NetBeans IDE and JDK softwares installed on your system .

Below are links available to Download NetBeans IDE and JDK .

Software or Resource Version Required
NetBeans IDE version 7.2, 7.3, 7.4, or 8.0
Java Development Kit (JDK) version 6, 7, or 8


 

Setting Up the Project :

 

  1. Start the NetBeans IDE .
  2. In the IDE choose  File> New Project as shown in below figure :

Step1

3. In the New Project expand the Java category and select Java Application as shown in the figure below . Than click Next :

Step2

4.In the Name and Location page of the wizard , do the following as shown in figure below :

  • In the Project Name field, type HelloWorldProject .
  • Leave the Use Dedicated Folder for Storing Libraries checkbox unselected .
  • In the Create Main Class field, type helloworldproject.HelloWorldProject .

 

cap6

5. Click on finish

The project is created and opened in the IDE. You should see the following components:

  • The Projects window, which contains a tree view of the components of the project, including source files, libraries that your code depends on, and so on.
  • The Source Editor window with a file called HelloWorldProject open.
  • The Navigator window, which you can use to quickly navigate between elements within the selected class.

Step4

Adding Code to the Generated Source File

Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE has created a skeleton main class for you. You can add the “Hello World!” message to the skeleton code by replacing the line:

            // TODO code application logic here

with the line:

            System.out.println("Hello World!");

Save the change by choosing File > Save.

The file should look something like the following code sample.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helloworldproject;

/**
 *
 * @author Amit Kumar
 */
public class HelloWorldProject {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
            System.out.println("Hello World!");
    }

}

Compiling and Running the Program

Because of the IDE’s Compile on Save feature, you do not have to manually compile your project in order to run it in the IDE. When you save a Java source file, the IDE automatically compiles it.

To run the program:

  • Choose Run > Run Project.

The next figure shows what you should now see.

Step5

To check whether a number is a Prime or Composite

A prime number is a whole number greater than 1 , whose only two  whole – number factors are 1 and itself . The first few prime numbers are as follows  2 ,3 ,5 ,7, 11, 13, 17, 19 , 23 , and so on .

All the whole numers greater than 1 which are not prime numbers are known as composite numbers . ie any number having factors more than 1 and itself . For example 4, 6, 8 , 9, 10 ,12 , 14 ,16 ,18 ,20.

import java.util.Scanner;

public class PrimeNumber{
public static void main(String[] args) {
int num ;
boolean isPrime = true;                                     // boolean data type is either true or false
System.out.println(“Enter any number : “);
Scanner sc = new Scanner(System.in);
num= sc.nextInt();                                         // taking input from user
for(int i=2;i<num /2;i++){                             // iterating till the value is half the num
if(num %i ==0){
isPrime =false;
break;
}
}
if(isPrime){
System.out.println(“The number “+num+” is a prime number .”);
}
else {
System.out.println(“The number “+num+” is a composite number .”);
}
}
}

PALINDROME IN JAVA

PALINDROME OF A NUMBER

A palindrome of a number is such that if we reverse it , it will not change . For example : number ‘12345321’ is apalindrome because its reverse also forms the same number . The number ‘12345’ is not a palindrome because its reverse ‘54321’ is not the same as ‘12345’ .
PROGRAM  FOR  PALINDROME  IN  JAVA
import java.util.Scanner;
public class Palindrome {

public static void main(String[] args) {
int t , n , r ,s =0;
System.out.println(“Enter any number : “);
Scanner sc =new Scanner(System.in);
n =sc.nextInt();          //taking value from the user
if(n<0){
System.out.println(“Enter any positive numbers  “);

}
else {
t =n;                 //assigning the value of n to t
while(n>0){
r =n%10;          //getting remainder
n=n/10;           //shorting the value of n
s =(s*10)+r;      //forming the reverse of a number

}
if(t ==s){
System.out.println(“The number “+t+” is a palindrome “);

}
else System.out.println(“The number “+t+” is not a palindrome “);

}
}
}