Archive for the ‘JAVA’ Category

Programs to demonstrate java basics

Posted: June 10, 2012 by bhumika289 in JAVA

Basic java program:

package javaapplication1;
public class JavaApplication1
{

/* This is my first java program.
* example of multi-line comments.
*/

public static void main(String[] args)
{
System.out.println(“This is a basic java program. Welcome to the programming world!!!!”);

//example of single line comment
}
}

Output:

This is a basic java program. Welcome to the programming world!!!!

Program to demonstrate objects and classes:

package Employee;

class Worker
{
String name;
int age;

void setData(String name1, int age1)
{
name=name1;
age=age1;
}
}
public class Employee
{
public static void main(String[] args)
{
int age=21;
Worker w=new Worker();
w.setData(“Makarand”, age);
System.out.print(“Name:”+w.name+”\nAge:”+w.age);
}
}

output:

Name:Makarand

Age:21

Program to demonstrate use of ‘if’ statement:

class Largest
{
public static void main(String args[])
{
int x1=10,x2=21,x3=3;
int large;
large = x1;
if (x2 > large)
large = x2;
if (x3 > large)
large = x3;
System.out.println(“Largest number=” + large);
}
}

Output:

Largest number=21

Program to demonstrate use of ‘if else’ statement:

class result
{
public static void main(String args[])
{
int marks = 40;
if (marks<40)
System.out.println(“The student has failed”);
else
System.out.println(“The student has Passed”);
}
}

Output:

The student has Passed

Program to demonstrate use of ‘if- else- if’ statement:

class result
{
public static void main(String args[])
{
int marks = 62;
if (marks<40)
System.out.println(“Fails”);
else if(marks>=40 && marks<60)
System.out.println(“Pass class”);
else if(marks>=60 && marks<75)
System.out.println(“First class”);
else
System.out.println(“Distinction”);
}
}

Output:

First class

Program to demonstrate use of nested if statement:

class Maximum
{
public static void main(String args[])
{
int a=10,b=21,c=3;
int max=0;
if (a>b) //1
{
if(a>c) //2
max=a;
else //2
max=c;
}
else //1
{
if(b>c) //3
max=b;
else //3
max=c;
}
System.out.println(“maximum=” +max);
}
}

Output:

maximum=21

Program to demonstrate use of ‘switch’ statement:

class Calculate
{
public static void main(String[] args)
{
int a=10,b=2,ch;
double ans;
ch=’3′;
switch(ch)
{
case 1:
ans=a+b;
System.out.println(“a+b=” + ans);
break;

case 2:
ans=a-b;
System.out.println(“a-b=” + ans);
break;

case 3:
ans=a*b;
System.out.println(“a*b=” + ans);
break;

case 4:
ans=a/b;
System.out.println(“a/b=” + ans);
break;

default:
System.out.println(“Incorrect choice”);
}
}
}

output:

a*b=20

Program to demonstrate use of ‘for’ loop:

class tableof5

{
public static void main(String args[])
{
int i;
for (i=1;i<=10;i++)
{
System.out.println(“5*”+i+”=”+(5*i));
}
}
}

output:

5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50

Program to demonstrate use of ‘while’ loop:

class tableof5

{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println(“5*”+i+”=”+(5*i));
i++;
}
}
}

output:

5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50

Program to demonstrate use of ‘do-while’ loop:

class tableof5

{
public static void main(String args[])
{
int i=1;
do
{
System.out.println(“5*”+i+”=”+(5*i));
i++;
}
while(i<=10);
}
}

output:

5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50

Program to demonstrate use of ‘break’ statement:

class break1
{
public static void main(String args[])
{
int i = 1;
while (i<=10)
{
System.out.println(i);
i++;
if (i==5)
{
break;
}
}
}
}

output:

12345

Program to demonstrate use of ‘labelled break’ statement:

class break2
{
public static void main (String args[])
{
boolean t=true;
first:
{
second:
{
third:
{
System.out.println(“third block, stmt1”);
if(t)
break third;
System.out.println(“third black, stmt2”);
}
System.out.println(“second block, stmt1”);
if(t)
break second;
System.out.println(“second black, stmt2”);
}
System.out.println(“first block, stmt1”);
if(t)
break first;
System.out.println(“first black, stmt2”);
}
}
}

output:

third block, stmt1
second block, stmt1
first block, stmt1

Program to demonstrate use of ‘continue’ statement:

class continue1
{
public static void main(String args[])
{
for (int i=1; i<=10; i++)
{
if (i%2 == 0)
continue;
System.out.println(i);
}
}

}

output:

13579

Program to demonstrate use of ‘return’ statement:

class Worker
{
String name;
int age;

void setData(String name1, int age1)
{
name=name1;
age=age1;
}
String getName()
{
return name;
}
int getAge()
{
return age;
}
}
public class Employee
{
public static void main(String[] args)
{
int age=21;
Worker w=new Worker();
w.setData(“Makarand”, age);
System.out.print(“Name:”+w.getName()+”\nAge:”+w.getAge());
}
}

output:

Name:Makarand
Age:21

Advertisements

Java Control Statements

Posted: June 10, 2012 by bhumika289 in JAVA

Selection Statements

1. if

2.switch

Allow you to control the flow of your program’s execution based upon conditions during run time.

1. if :

  • It is a conditional branch statement.
  • Can be used to route program execution through two different paths.

Syntax :

if (condition)

{

statements;

}

  • When the condition is true the Statement within the if is executed and execution continues with the next statement after the if statement.
  • If the condition is false then the statement within the if is not executed and the execution continues with the statement after the if statement.
  • If the number of statement in if block is only one then parentheses are optional but if its more than one than parentheses are compulsory.

if else :

Syntax :

if (condition)

{

statement1;

}

else

{

statement2;

}

  • If the condition is true, then statement1 is executed.
  • Otherwise, statement2 is executed.

if-else-if Ladder :

Syntax :

if(condition)

statements;

else if(condition)

statements;

else if(condition)

statements;

else

statements;

  • As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder statements are bypassed.
  • If none of the conditions is true, then the final else statement will be executed.

Nested if :

A nested if is an if statement that is the target of another if or else.

Syntax :

if(condition)

{

if(condition)

statements….

else

statements….

}

else

{

if(condition)

statements….

else

statements….

}

2. switch :

  • Multiway branch statement.
  • Provides an easy way to dispatch execution to different parts of your code based on the value of an expression.

Syntax :

switch (expression)

{

case value1 :

statement1 ;

break;

case value2 :

statement2 ;

break;

case valuen :

statementn ;

break;

default :

statements ;

break;

}

  • The expression must be of type byte, short, int, or char and each of the values specified in the case statements must be of a type compatible with the expression.
  • Each case value must be a unique literal.
  • The value of the expression is compared with each ‘case’ values. If a match is found, the corresponding statement or statements are executed.
  • If no match is found, statement or statements in the default case are executed. Default statement is optional.
  • If default statement is absent, then if no matches are found, then the switch statement completes without doing anything.
  • The break statement is used inside the switch to terminate a statement sequence.

Looping Statements

1. for

2. while

3. do while

A loop repeatedly executes the same set of instructions until a termination condition is met.

1. for :

  • Repeats a set of statements a certain number of times until a condition is matched.
  • Entry controlled loop, as condition is checked while entering the loop.

Syntax :

for (initialization; condition; expression)

{

Set of statements;

}

  • In the first part a variable is initialized to a value.
  • The second part consists of a test condition that returns only a Boolean value.
  • The last part is an expression, evaluated every time the loop is executed.

2. while :

  • Executes a set of code repeatedly until the condition returns false.
  • Entry-controlled loop.

Syntax :

while (condition)

{

body(statements) of the loop

}

  • <condition> is the condition to be tested.
  • If the condition returns true then the statements inside the <body of the loop> are executed.
  • Else, the loop is not executed.

3. do while :

  • Similar to the while loop except that the condition to be evaluated is given at the end.
  • Hence the loop is executed at least once even when the condition is false.
  • Exit-controlled loop.

Syntax :

do

{

body of the loop

} while (condition);

In do while loop semicolon(;) is compulsory after while.

Jump Statements

1. break

2. continue

3. return

These statements transfer control to another part of your program.

1. break:

  • This statement is used to jump out of a loop.
  • On encountering a break statement within a loop, the execution continues with the  next statement outside the loop and the remaining statements which are after the break and within the loop are skipped.
  • Break statement can also be used with the label of a statement.
  • A statement can be labeled as follows.

statementName : SomeJavaStatement

  • When we use break statement along with label the execution continues with the statement having the label.

break statementName;

2. Continue:

  • Used only within looping statements.
  • When the continue statement is encountered, the next iteration starts.
  •  The remaining statements in the loop are skipped. The execution starts from the top of loop again.

3. return:

  • Used to explicitly return from a method.
  • Causes program control to transfer back to the caller of the method.
  • Immediately terminates the method in which it is executed.

Fundamentals of Java

Posted: June 9, 2012 by bhumika289 in JAVA

Identifiers

Identifiers are names used for classes, variables and methods. Points to remember:

  • All identifiers should begin with a letter (A to or a to z ), currency character ($) or an underscore (-).  eg. $name, _name, __1_name ,name
  • After the first character identifiers can have any combination of characters.
  • A keyword cannot be used as an identifier.
  • Identifiers are case-sensitive.

Keywords

The following list shows the reserved/keywords in Java.

abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while

Variables

  • Basic unit of storage in a java program.
  • Every variable has scope and life time throughout the program.
  • A block is begins with an opening curly brace and ends with a closing curly brace.A block defines a scope.
  • Most other computer languages define two categories of scopes: global and local.

Declaring variables:
syntax:       type identifier1=val , identifier2; where,

  • type: datatype or classname.
  • identifier: variable name.
  • optional initializer to directly initialize the variable with a value.
example:
    int a = 29, b;

 Dynamic Initialization:Variables can be initialized dynamically as shown below:

    int a = 29, b;
b= a*a;

Symbolic Constants

  • Value is fixed within the scope.
  • Declared using the ‘final’ keyword.

example:

    final double PI = 3.414;

Java Literals

  • Representation of a fixed value.
  • Can be assigned to any primitive type variable.

example:

    int a = 29;
String s = “Welcome to Engineering Adda”;

Escape sequences for String and char literals:

Notation

Character represented

\n Newline
\r Carriage return
\f Formfeed
\b Backspace
\s Space
\t Tab
\” Double quote
\’ Single quote
\\ backslash
\ddd Octal character
\uxxxx Hexadecimal UNICODE character

Data Types in Java

There are two data types available in Java:

  1. Primitive Data Types
  2. User-defined Data Types

1. Primitive Data Types:

Primitive Data Types

2. User-defined Data Types:

  • Reference variables are created using defined constructors of the classes.
  • They are used to access objects.
  • These variables are declared to be of a specific type that cannot be changed.
  • Class objects, and various type of array variables come under reference data type.
  • Default value of any reference variable is null.
  • A reference variable can be used to refer to any object of the declared type or any compatible type.

example:

     Fruit fruit = new Fruit(“apple”);

Operators

Symbol that tells the computer to perform mathematical and logical calculation.   Arithmetic Operators:

Operator Description Example
+ Addition – Adds values on either side of the operator A=10, B=12, A + B=22
Subtraction – Subtracts right hand operand from left hand operand A=10, B=12, A – B=-2
* Multiplication – Multiplies values on either side of the operator A=10, B=12, A * B=120
/ Division – Divides left hand operand by right hand operand A=10, B=10, B / A will give 1
% Modulus – Divides left hand operand by right hand operand and returns remainder A=10, B=9, B % A will give 1
++ Increment – Increase the value of operand by 1 B=20, B++ gives 21
Decrement – Decrease the value of operand by 1 B=20, B– gives 19

Relational Operators:

Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. A=19, B=20, (A == B)=false.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. A=19, B=20, (A != B)=true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. A=19, B=20, (A > B)=false.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. A=19, B=20, (A < B)=true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. A=19, B=20, (A >= B)=false.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. A=19, B=20, (A <= B)=true.

Bitwise Operators:

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. A=0011, B=1110, (A & B)=0010i.e. A=3, B=15, (A & B)=2
| Binary OR Operator copies a bit if it exists in eather operand. A=0011, B=0110, (A | B)=0111i.e. A=3, B=6, (A | B)=7
^ Binary XOR Operator copies the bit if it is set in one operand but not both. A=1010, B=0011, (A ^ B)=1001i.e. A=10, B=3, (A ^ B)=9
~ Binary Ones Complement Operator is unary and has the efect of ‘flipping’ bits. A=0011, (~A)=1100i.e. A=3, (~A)=12
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A=0001, A << 2 =0100i.e. A=1, A << 2 =4
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A=0100, A >> 2 =0001i.e. A=4, A >> 2 =1
>>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A=1101, A >>>2 =0010i.e. A=13, A >>>2 =2

Logical Operators:

Operator Description Example
&& Called Logical AND operator. If both the operands are non zero then then condition becomes true. A=11, B=01, (A && B) is false.
|| Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. A=11, B=01, (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. A=11, B=01, !(A && B) is true.

Assignment Operators:

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A equivalent to C = C – A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 same as C = C | 2

Conditional Operator ( ? : ):

  • Also known as the ternary operator.
  • Consists of three operands.
  • Used to evaluate boolean expressions.
  • The goal of the operator is to decide which value should be assigned to the variable.

syntax:     variable x = (expression) ? value if true : value if false   instanceOf Operator:

  • Used only for object reference variables.
  • Checks whether the object is of a particular type(class type or interface type).

syntax:   ( Object reference variable ) instanceOf  (class/interface type)
Precedence of Java Operators:

Category  Operator  Associativity 
Postfix () [] . (dot operator) Left to right
Unary ++ – – ! ~ Right to left
Multiplicative * / % Left to right
Additive + – Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

Introduction to java programming

Posted: June 6, 2012 by makaranddalal in JAVA

It was developed by Sun Microsystems, released in 1995.

Features of java

  • Object Oriented: Everything in java is an object.
  • Platform independent: Java code is compiled into platform independent byte code and interpreted by JVM on whichever platform it is run.
  • Simple: Easy to learn and understand.
  • Secure: Helps to develop virus-free code. Public key encryption is provided for authentication.
  • Architectural- neutral: Architecture-neutral object file format which makes the compiled code to be executable on many processors.
  • Portable: Compiler and Java is written in ANSI C with a clean portability boundary which is a POSIX subset.
  • Robust: Supports both compile time error checking and runtime checking.
  • Multi-threaded: Possible to write programs that can do many tasks simultaneously.
  • Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere.
  • High Performance: With the use of Just-In-Time compilers.
  • Distributed: Designed for the distributed environment of the internet.
  • Dynamic: Designed to adapt to an evolving environment. Resolves accesses to objects on run-time.

Requirements

  • Windows 95/98/2000/XP or Linux 7.1 operating system.
  • Java JDK 5
  • Microsoft Notepad / Netbeans 7.1

Software Download

Steps to be followed

1. Write a java program:
Components of a java program include:

  • Class: A class can be defined as a template that describe the behaviors and states that object of its type support.
  • Methods: Behavior is defined in the methods. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
  • Instance Variables: Each object has its unique set of instance variables.
  • Object: Objects have states and behaviors. An object is an instance of a class.

Points to be remembered:

  • Everything is enclosed in a class (including main() method).
  • No terminating semicolon for a class.
  • At least one main method.
  • Execution starts at main.
  • main() method takes one argument – array of strings.
  • Each statement ends with a semicolon.
  • In Netbeans, new project is created using ctrl+shift+N and new file using ctrl+N.

2. Save the program:

  • File name should be same as class name.
  • Include the extension “.java”.
  • The file should be saved in the bin folder (eg. in C:\Program Files\Java\jdk1.7.0\bin) or proper path is provided by setting the environment variables of the system.

3. Compile the program:

  • A “.class” file is created containing the byte code.
  • Open the command prompt and change the directory to the one in which the program file is saved.
  • Compile the code using the command “javac programname.java”.
  • If you are using Netbeans, press F11.

4. Run the program:

  • Use the command “java programname”.
  • Specify command line arguments, if any, using a space as separator.
  • In Netbeans, command line arguements are specified in properties/run of the project. Program is run using F6.