• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Java

Java Class Rectangle Example

By Dinesh Thakur

When you compile this program, you will find that two class files have been created, one for Rectangle and one for RectangleArea. The Java compiler automatically puts each class into its own class file.

To run this program, you must execute RectangleArea class. This is because the main () method is in this RectangleArea class and not in Rectangle class.

class Rectangle 
{
      int length;
      int breadth;
      //method to intialize length and breadth of rectangle
      void setData(int l, int b)
      {
        length =l;
        breadth=b;
      }
      //method to calculate area of rectangle
      int area()
      {
        int rectArea;
        rectArea = length * breadth;
        return rectArea;
      }
}
//Class to Create Rectangle Objects and Calculate Area
class RectangleArea
{
         public static void main(String[] args)
     {
           //Creating objects
           Rectangle firstRect = new Rectangle();
           firstRect.setData(5,6);
           int result = firstRect.area();
           System.out.println("Area of Rectangle = "+ result);
     }
}

Java Class Rectangle

In this Example, we have declared two classes: Rectangle and RectangleArea. The Rectangle class contains two fields length and breadth of type int that correspond to the length and breadth of the rectangle respectively. In addition, the Rectangle class also contains two methods named setData () and area ().The method setData () initializes length and breadth fields of an object and area ()calculates the area of the rectangle. It does not have a main () method and therefore cannot be run. It is merely a definition used to define and create Rectangle objects. So we define another class named RectangleArea that contains the main () method from where the program execution actually begins.

In the main (), the statement

Rectangle firstRect = new Rectangle();

creates a Rectangle object in memory and assign it to the reference variable firstRect

The statement,

firstRect.setData(5,6);

invokes the method setData () on the object firstRect, and copies the arguments 5 and 6 to the parameters l and b respectively. The flow of control is now within the body of the setData () method. Here, the values in l and b are assigned to length and breadth instance variables respectively. After executing the body of the setData () method, the control now shifts back to the main () method and continues with the next statement,

int result = firstRect.area();

Here, the area () method is invoked on the firstRect object, causing flow of control to jump to the area () method. In this method, we declare the variable rectArea which exist only within the body of the method. This variable will be created each time you the method are executed and will be destroyed when execution of method ends. All the variables you declare within the body of the method are local to the method and are only around while the method is being executed. These variables are known as local variables.

In this variable, we store the area of the rectangle using the statement,

rectArea = length*breadth;

After this, the return statement is reached, which in this example returns the value 30 and also causes the flow of control to jump back to the calling method, main (). The value is 30 is then substituted for the method name from where it is called which is then assigned to the variable result. This value is then displayed using the

Systerm.out.println () method.

Java Program Vowel or Not Example

By Dinesh Thakur

In the switch statement, since same statements has to be executed corresponding to different cases (‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’) so we write the statements with the last case. The break statement causes the switch statement to terminate when any of the vowels is entered. [Read more…] about Java Program Vowel or Not Example

Program To Show Importance of Continue Statement? Java Example

By Dinesh Thakur

In this example, the continue statement is placed in the body of inner for loop. While executing inner for loop, if the condition (m==n) evaluates to true then the continue statement is executed and the remaining statement for displaying values of m and n is skipped and control is transferred to the increment expression (n++) of inner for loop. This increments the value of n by 1 and test condition (n<=2) is evaluated again for this incremented value of n. This process continues. We have used continue statement in this program so that the same value of m and n should not be displayed. [Read more…] about Program To Show Importance of Continue Statement? Java Example

Java Calculate The Sum Of Only The Positive Numbers. Example

By Dinesh Thakur

This example computes the sum of positive numbers input by the user. When a negative number is input, the condition (num<0) become true and break statement is executed which leads to the termination of the while loop and the next statement following the loop is executed which displays the sum of positive numbers. The condition of the while loop always remains true as we have specified a non-zero value 1 which makes it run infinitely. The only way to exit this loop is to. use break statement. [Read more…] about Java Calculate The Sum Of Only The Positive Numbers. Example

Break Statement Java Example

By Dinesh Thakur

The break statement terminates the execution of the loop in which it is defined and the control is transferred immediately to the next executable statement after the loop. The break statement is normally used with either while, do-while, for or a switch statement. It is mostly used to exit early from the loop by skipping the remaining statements of loop or switch control structures.

It is simply written as

break;

//Program to Show Importance of Break Statement 
public class ImpBreak
{
       public static void main(String[] args)
    {
         System.out.println("Show Importance of Break Statement");
         for(int i=1; i<=10;i++)
             {
                  System.out.println("i = "+i);
                  if(i==5)
                   {
                       System.out.println("\nBye");
                       break;
                   }
             }
     }
}

Break Statement Java Example

In this example, the for loop executed starting from i=1 to 10 in steps of 1. Now when the condition (i==s)in the body of the loop is satisfied, the break statement causes the control to move out of for loop

Java Nested For Loop Examples

By Dinesh Thakur

Like the nesting of if and other looping statements, the for loop can also be nested. In other words, we can have a for loop in the body of other for loop. There is no restriction on the level of nesting of loops but one should take care while nesting at multiple levels otherwise unexpected results may arise. [Read more…] about Java Nested For Loop Examples

Solve Equation 3*x*x – 2*x +1 in Java Example

By Dinesh Thakur

In this example, we input the interval values a and b. Each time loop is executed the value of fx is calculated and displayed on the screen for the value of x which ranges from a to b. On each iteration, x is incremented by 0.05. This continues until x is less than equal to the value of b that user inputs. [Read more…] about Solve Equation 3*x*x – 2*x +1 in Java Example

Java Program to Find Average of N Numbers

By Dinesh Thakur

In this example, we input number of elements n (i.e.) whose average is to be calculated. When for loop begins executing, the loop control variable i is declared and initialized to 1. Then the test condition (i<=n) is checked. As it is true in this case because (1<=5) and the statements in the body of the loop are executed which inputs the first number (5 in our case) and add this value to variable sum. Then the increment expression i++ increases the value of variable i by 1 (i+ 1=2). After one complete iteration, the test condition in the for loop is checked again which is true again as (2<=5) and the body of the loop is executed again. This process continues until the loop control variable (i) is incremented to 6. Now when the test condition (6<=5) is evaluated again it becomes false and the execution of for loop terminates and control transfers to the next statement following the for loop that calculates the average of n (5) numbers which is then displayed. [Read more…] about Java Program to Find Average of N Numbers

Sum of First N Natural Numbers in Java Example

By Dinesh Thakur

In this example, the sum of first 10 natural numbers is displayed. First, input the value of n (10 in this case) i.e. number of natural numbers whose sum is to be calculated. Then, after initializing the variables i to 1 and sum to 0, we enter the do-while loop. The execution of the body of loop continues as long as condition (i<=n) evaluates to true. When variable 1’s is value becomes 11, the condition becomes false and this terminates the do-while loop and program execution continues with the next statement after the loop which displays the sum of first 10 natural numbers. [Read more…] about Sum of First N Natural Numbers in Java Example

Sum of Digits of a Number in Java Example

By Dinesh Thakur

In this program, we first input the number (Say num = 12345). Next the control reaches the while loop where it checks the condition (num>0) which is true as (12345>0) so the body of the loop is executed. [Read more…] about Sum of Digits of a Number in Java Example

Explicit Type Conversion (Type Casting)

By Dinesh Thakur

In addition to the implicit type conversion, Java also provides the facility of explicit type conversion within an expression. In implicit type conversion, a value of lower data type is converted to a value of higher data type. This results in no loss of information. However, if you try to convert a value of higher data type to that of lower data type then java compiler generates an error message “possible loss of precision”. For example:

float i = 12.50;

But if you want to force this conversion which may result in loss of information then this can be accomplished using explicit type casting.

Using explicit type casting, we can override Java’s default type conversions by explicitly specifying our own temporary data type according to the requirements. When we type cast a value, its data type is changed temporarily from its declared data type to the new data type. To explicit type cast, give the target type in parentheses followed by the variable’s name or the value to be cast.

(target_data type) operand;

For example:

float height = (float)5.5;

int d = (int ) (a/b); // Here a and b are of double type

In the first example, integer literal 5.5 is converted to float type and result is stored in variable height. The cast is necessary because there is no automatic conversion from double to float. In the second example, the outcome of the expression is converted to into Parentheses surrounding a/b is necessary, otherwise the cast to int will only apply to a and not to the outcome of the result.

Explicit type conversion is also known as narrowing a type. The explicit type casting is important in situations where the fractional part of a number is to be preserved. E.g. If you want to calculate the percentage marks of student appearing in examination in five different subjects of 100 marks each and suppose that total marks obtained is stored in a variable tot_marks_obt of type int, then on executing the statement.

per = tot_marks_obt/5;

gives you the percentage as an integer value and fractional part will be ignored. Thus in

this case, to retain fractional part you need to cast variable tot _marks _ obt to type double before dividing it by 5 as shown in the following statement.

per = (double)tot_marks_obt/5;

In the above statement, the type of variable tot_marks_obt is converted explicitly into double data type and stored in temporary variable of type double which is then divided by 5.0 (implicitly conversion from int to double) and this percentage calculated in fraction form stored in variable per. Here, the conversion does not change the original data type of operand and type is temporarily changed within the expression.

To illustrate the concept of explicit typecasting, let us consider a program to convert temperature given in Fahrenheit to one in Celsius.

/* Program to Convert temperature given in Fahrenheit to celsius using Explicit type conversion */

class ExplicitTypeConversion

{

         public static void main(String args[])

    {

          double c;

          double f=96;

          c = (double) 5/9 * (f-32);

           System.out.println(“Temperature in Celcius is : ” +c);

     }

}

Final Variable (OR Constant Variable) in Java with Example

By Dinesh Thakur

Variables are useful when you need to store information that can be changed as program runs. However, there may be certain situations in the program in which the value of variable should not be allowed to modify. This is accomplished using a special type of variable known as final variable. The final variable also called constant variable. It is a variable with a value that cannot be modified during the execution of the program. [Read more…] about Final Variable (OR Constant Variable) in Java with Example

Java Program Structure

By Dinesh Thakur

Java Program Structure: A Java program consists of different sections. Some of them are mandatory but some are optional. The optional section can be excluded from the program depending upon the requirements of the programmer. [Read more…] about Java Program Structure

Types of Java Programs

By Dinesh Thakur

Java is a robust, general-purpose, high-level programming language and a powerful software platform. It is also object-oriented, distributed, portable and multi-threaded. Java follows the ‘Write – once – run – anywhere’ approach. All Java programs must run on the Java platform that has two components, the Java Virtual Machine (JVM) and the Java Application Programming Interface (API). [Read more…] about Types of Java Programs

Mathematical Operations in Java Example

By Dinesh Thakur

Most of the computer languages typically support advanced math operations (such as square root, trigonometric sine, cosine etc.) by way of function libraries. Java also provides a range of methods that support such functions in the standard libraries Math class stored in the package java.lang. Java’s Math class contains a collection of methods and two constants that compute standard mathematical functions.

All the methods and constants available in the Math class are static; so they can simply be referred by just writing class name Math and name of the method or constant you want to use separated by a period (.)

//Program to Show various Methods of Math Class
 public class MathematicalOperations
{
       public static void main(String [] args)
   {
          System.out.println("Absolute value -16 = " + Math.abs(-16));
          System.out.println("Sine of va1ue PI/2= " + Math.sin(Math.PI/2));
          System.out.println("Arc Cosine of -1  = " + Math.acos(-1));
          System.out.println("Upper limit of 7.8 = "+ Math.ceil(7.8));
          System.out.println("Lower limit of 7.8 = "+ Math.floor(7.8));
          System.out.println("Maximum of 15 and 20 = " +Math.max(15,20));
          System.out.println("Rounded value = " + Math.round(7.68));
          System.out.println("Square root of 4 = " + Math.sqrt(4.0));
          System.out.println("2 power 3 is  = " + Math.pow(2.0,3.0));
          System.out.println("Log of 1000 = " + Math.log(1000.0));
   }
}

Mathematical Operations in Java Example

Implicit Type Conversion in Java Example

By Dinesh Thakur

The conversion of a data type which is carried out automatically by the compiler without programmer intervention is called the implicit type conversion. When two variables of different data types are involved in the same expression, the Java compiler uses built-in library functions to trans- form the variables to common data type before evaluating the expression. To decide which variable’s data type is to be converted, the Java compiler follows certain rules and converts the lower data type to that of a higher data type. This is known as widening a type.

 

The rules in the sequence in which they are checked are as follows.

1. If one of the operands is double, the other is promoted to double before the operation is carried out.

2. Otherwise, if one of the operands is float, the other is promoted to float before the operation is carried out.

3. Otherwise, if one of the operands is long, the other is promoted to long before the operation is carried out.

4. Otherwise if either operand is int, the other operand is promoted to int.

5. If neither operand is double, float, long or int, both operands are promoted to int.

//Program to Show Implicit Type Conversion  
public class ImplicitTypeConversion
{
         public static void main (String[] args)
     {
           byte  i=10;
           long  j=1+8;
           double k=i*2.5 +j;
           System.out.println("I =" +i);
           System.out.println("J =" +j);
           System.out.println("K =" +k);
      }
}

Implicit Type Conversion in Java Example

Conditional Operator in Java with Example

By Dinesh Thakur

Conditional operator (?:) is the only ternary operator available in Java which operates on three operands. The symbol “?” placed between the first and the second operand , and ” : ” is inserted between the second and third operand. The first operand (or expression) must be a boolean . The conditional operator together with operands form a conditional expression which takes the following form.

expr1? expr2:expr3

where expr1 is a boolean expression and expr2 and expr3 are the expressions of any type other than void. The expr2 and expr3 must be of the same type.

 

If expr1 has value true, the operator returns a result expr2 .
If expr1 has value false, the operator returns a result expr3 .

During the  calculates the value of the first argument . if it has the true value , then calculates the second (middle ) argument returned as a result . However , if the calculated result of the first argument is false, then it is given the third ( last ) argument the returned as a result. Here is an example of the use of the operator ” ? ” :

//Program to Find greatest of three numbers using Conditional Operator
 import java.util.Scanner; //program uses Scanner class
public class ConditionalOperator
{
        public static void main(String[] args)
    {
          int a,b,c,result;
          //create Scanner object to obtain input from keyboard
          Scanner input=new Scanner(System.in);
          System.out.print("Enter the Three Number : "); //prompt for input
          a=input.nextInt();   //Read First number
          b=input.nextInt();   //Read Second number
          c=input.nextInt();   //Read third number
          result = (a>b)? ((a>c)?a:c) : ((b>c)?b:c);
          System.out.println( result  + " is Greatest");
    
     }
 }

Conditional Operator in Java with Example

Bitwise Operators in Java Example

By Dinesh Thakur

Java provides an extensive bit manipulation operator for programmers who want to communicate directly with the hardware. These operators are used for testing, setting or shifting individual bits in a value. In order to work with these operators, one should be aware of the binary numbers and two’s complement format used to represent negative integers.

The bitwise operators can be used on values of type long, int, short, char or byte, but cannot be used with boolean, float, double, array or object type.

The bitwise AND (&) bitwise OR (!) and bitwise Exclusive OR (^)are the three logical bitwise operators. These are the binary operators which compare the two operands bit by bit. If either of the operands with a bitwise operator is of type long then the result will be long, otherwise the result is of type int.

Bitwise AND (&)operator combines its two integer operands by performing a logical AND operation on their individual bits. It sets each bit in the result to 1 if corresponding bits in both operands are 1. One of the applications of bitwise AND operator is forcing selected bits of an operand to 0.

Bitwise OR (|)operator combines its two integer operands by performing a logical OR operation on their individual bits. It sets each bit in the result to 1if the corresponding bits in either or both of the operands are 1. One of the applications of bitwise OR is forcing selected bits of an operand to 1.

Bitwise Exclusive OR operator (^) combines its two integer operands by performing a logical XOR operands on their individual bits. It sets each bit in the result to 1 if the corresponding bits in two operands are different. One of the applications of bitwise Exclusive OR operator is to change 0’s to 1’s and l’s to 0’s.

Bitwise One’s Complement operator (-) Bitwise complement operator (-) is a unary operator. It inverts each bit of its operand i.e. Is become Os and Os become Is. This operator can be used to

1.  To encrypt the contents of a file which can later be decrypted.

2.  To store negative numbers in some computers that supports one’s complement method for storing negative number.

Let us consider an operand a = 0000 0000 0001 0010 then on performing (~a) we get

-a = 1111 1111 1110 1101

Bitwise shift left operator (<<) shifts the bits of the left operand to left by number of positions specified by the right operand. The high order bits of the left operand are lost and 0 bits are shifted in from the right .It has the following syntax

Operand1 << operand2

Here, operand1 is binary representation of a number to be the shifted and operand2 represents the number of positions by which it is shifted.

Bitwise Shift Right operator (>>)shifts the bits of the left operand to right by a number of positions specified by the right operand. The low order bits of the left operand are lost and the high order bits shifted in are either 0 or 1 depending upon whether the left operand is positive or negative. If the left operand is positive, Os are shifted into the high order bits and if the left operand is negative, 1’s are shifted instead. It has the following syntax.

operand1>>operand2

Here, operand1 is the binary representation of a number to be shifted and operand2 represents the number of positions by which it is shifted.

Bitwise Shift Right with zero fill (>>>) operator is similar to bitwise shift right (>>) operator with the exception that it always shifts zero’s into the high order bits of the result regardless of the sign of the left hand operand.

//program Showing bitwise Operators 
import static java.lang.Long .*;
 public class BitwiseOperators
 {
    public static void main (String [] args)
    {
       Short x=20,y=0xaf ;
       Short z= -24;
       System.out.println(" x & y --> " + (x & y));
       System.out.println(" x | y --> " + (x | y));
       System.out.println(" x ^ y --> " + (x ^ y));
       System.out.println(" z << 2 --> " + (z<<2));
       System.out.println(" z >>> 2 --> " +  (z>>>2));
       System.out.println(" z >> 2 --> " + (z>>2));
      
    }
 }

Bitwise Operators in Java Example

Logical Operators in Java Examples

By Dinesh Thakur

Logical operators are used to combine one or more relational expressions that results in formation of complex expressions known as logical expressions. Like relational operators, the logical operators evaluate the result of logical expression in terms of Boolean values that can only be true or false according to the result of the logical expression.

In Java, there are six logical operators: logical AND (&), logical OR (|), logical exclusive

OR i.e. XOR (^), logical negation (!), conditional AND (&&), conditional OR  (||). All the logical operators are binary operators except logical negation which is a unary operator. The logical AND (&) operator evaluates to true if and only if both its operands evaluates to true. The logical OR (I) operator evaluates to true if and only if either of its operands evaluate true. The logical exclusive OR i.e. XOR (^) operator evaluates to true if and only if either, but not both, of its operands are true. In other words, it evaluates to false if both the operands are false.

The logical NOT(!) operator takes a single operand and evaluates to true if the operand is false and evaluates to false if the operand is true.

 

Table shows you the different Logical Operators used in Java Programming

 

                                                             Logical Operators

 

Operators

Meaning

&&

||

!

Logical AND

                                    Logical OR

Logical NOT

 

The logical operators && and || are used when we want to form compound conditions by combining two or more relations. Logical operators return results indicated in the following table.

 

x

Y

X && Y

X || Y

T

T

F

F

T

F

T

T

T

F

F

F

T

T

T

F

 

//program Showing Logical Operations
public class LogicalOperators
{
    public static void main (String [] args)
    {
       int x=6 ,y=4,z=5;
       System.out.println(" x>y & y>z-->" + (x>y & y>z));
       System.out.println(" x>y | y>z-->" + (x>y | y>z));
       System.out.println(" x>y ^  y>z-->" +(x>y  ^ y>z));
       System.out.println(" x>y && y>z-->"  +  (x>y&& y>z));
       System.out.println(" x>y || y>z-->"  +  (x>y||y>z));
       System.out.println(" !(x>y)--> " + (!(x>y)));  
    }
    
}

Logical Operators in Java Examples

Java Example to implement Logical Operators using Scanner Class. 
import java.util.*;
import java.lang.*;
class LogicalOperatorsUsingScanner
{
              public static void main(String args[])
         {
                  int x,y,z;
                  Scanner scan = new Scanner(System.in);
                  System.out.print("Enter the Value of x : ");
                  x=scan.nextInt();
                  System.out.print("Enter the Value of y : ");
                  y=scan.nextInt();
                  System.out.print("Enter the Value of z : ");
                  z=scan.nextInt();
                  System.out.println("x>y and x>z : "+((x>y) &&(x>z)));
                  System.out.println("x not equal to z : "+(x!=z));
          }
}

Java Example to implement Logical Operators using Scanner Class

Relational Operators in Java Example

By Dinesh Thakur

Relational operators also known as comparison operators are used to check the relation between two operands. In other words, the operators used to make comparisons between two operands are called relational operators. Relational operators are binary operators and hence require two operands. The result of a relational operation is a Boolean value that can only be true or false according to the result of the comparison.

Relational operators are normally used with if statements, while loop, do-while loop and for loop to make branching and looping decisions.

 

Table shows you the different relational operators used in java programming.

 

                                                          Relational Operators

 

Operator

Operations

Example

< 

> 

<=

>=

==

!=

Less than

Greater than

Less than or equal to

Greater than equal to

Equal to

Not equal to

x<y

x>y

x<=y

x>=y

x=y

x!=y

 

//program Showing Relational Operations
  public class RelationalOperators
{
       public static void main (String[] args)
    {
          int x=5 ,y=3;
          System.out.println("x  > y --> " + (x>y));
          System.out.println("x  < y --> "  + (x<y));
          System.out.println("x <= y --> " + (x<=y));
          System.out.println("x >= y --> " + (x>=y));
          System.out.println("x == y --> " + (x==y));
          System.out.println("x != y --> " + (x!=y));
      
     }
}

Relational Operators in Java Example

Java Example to Perform Relational Operations Using Scanner Class. 
import java.util. *;
class RelationalOperationsUsingScanner
{
          public static void main(String args[])
       {
                int x,y;
                Scanner scan = new Scanner(System.in);
                System.out.print("Enter the Value of x : ");
                x=scan.nextInt();
                System.out.print("Enter the Value of y : ");
                y=scan.nextInt();
                System.out.println("x>y : "+(x>y));
                System.out.println("x<y : "+(x<y));
                System.out.println("x>=y : "+( x>=y));
                System.out.println("x<=y : "+( x<=y));
        }
}

Java Example to Perform Relational Operations Using Scanner Class

Arithmetic Operators in Java Examples

By Dinesh Thakur

The Arithmetic operators are used to perform arithmetic operations. The Arithmetic operators are binary operators that work with integers, floating point numbers and even characters (i.e. they can be used with any primitive type except the boolean).

There are five arithmetic operators available in Java which include addition (+), subtraction (-), multiplication (*), division (/) and modulus (%) operator. The modulus operator tells us what would be the remainder after integer division is performed on a particular expression. Unlike C/C++, the modulus operator can also be applied to floating point values. The rest of the operators have same meaning as they have in mathematics.

The operands acted on by arithmetic operators must represent numeric values. Thus the operands can be integer quantities, floating point quantities or characters. The Arithmetic operators when used with characters operate on Unicode values of the characters.

The result of division of one integer quantity by another is referred to as integer division as this operation results in a quotient without a decimal point. On the other hand, if division is carried out with two floating point numbers or with one floating point and one integer number, the result will be a floating point quotient.

//Program Showing Arithmetic Operations
public class ArithmeticOperators
 {
          public static void main (String[] args)
      {
            float x=10.5f ,y=2.3f ;
            System.out.println(" x+y = " + (x+y));
            System.out.println(" x-y = " + (x-y));
            System.out.println(" x*y = " + (x*y));
            System.out.println(" x/y = " + (x/y));
            System.out.println(" x%y = " + (x%y));
      
       }
 }

Arithmetic Operators in Java Examples

Java Example to Perform Arithmetic Operation Using Scanner Class. 
 
import java.util. *;
class ArithmeticOperatorsUsingScanner
{
           public static void main(String args[])
       {
                 int a,b;
                 Scanner scan=new Scanner(System.in);
                 System.out.print("Enter the Value of a : ");
                 a=scan.nextInt();
                 System.out.print("Enter the Value of b : ");
                 b=scan.nextInt();
                 System.out.println("Addition is : " +(a+b));
                 System.out.println("Subtraction is : "+( a-b));
                 System.out.println("Multiplication is : "+( a*b));
                 System.out.println("Division is : "+( a/b));
                 System.out.println("Modulus is : "+( a%b));
       }
}

Java Example to Perform Arithmetic Operation Using Scanner Class

Java Input Program Example

By Dinesh Thakur

We will now make a small program that will input two integers in Java and display their sum. In this program, we will use the methods available in Scanner class to read data typed at keyboard and place it into variables that we specify. [Read more…] about Java Input Program Example

Moving Ball Using Thread in Java Example

By Dinesh Thakur

[Read more…] about Moving Ball Using Thread in Java Example

Types of Thread in Java

By Dinesh Thakur

Thread is a lightweight process. It is lightweight because they utilize the minimum resources of the system. Thread is an independent concurrent path of execution of a group of statements. Thread takes less memory and less process time.

Threading is a technique to allow multiple activities to execute simultaneously within the single process.

Types of Thread

1. Daemon Thread or System defined Thread e.g-Garbage collector user defined Thread

How to create user defined thread. Programmer creates user defined thread in two ways. By implementing Runnable interface

1st- the class must implement the Runnable interface, construct the object of the class and this object is treated as Runnable object.

2nd- construct the Thread class object by passing runable object as an argument

3rd- call the start method of Thread class to execute the thread and make the thread eligible to run.

4th- Programmer bound override the run method of the Runnable interface to move thread into running state. start method implicitly call run method.

By extending Thread class

1st- the class must extends the Thread class and must override the run method Thread class.

2nd- Within the child class constructor, programmer is bound to explicitly call the base class parameterized constructor (by using super keyword), otherwise child class constructor implicitly call base class default constructor.

3rd- call the start method of Thread class to make thread eligible to run.

4th- Start method implicitly calls the override rum method.

Get Pixel Color BufferedImage Java Example

By Dinesh Thakur

The color class is used to manipulate colours using the methods and constants defined in it. Every colour is a combination of red, green and blue. Combinations of these three colours, which take values from 0 to 255 or 0.0 to 1.0, can generate any new colour. Therefore, the Color class has two constructors, one takes integer parameters and another takes float parameters.

 

public Color( int r, int g. int b ) ;

public Color( float r, float g. float b ) ;

 

The Graphics class has the methods set and get which can be used to set the colour of the object that is being drawn and to get the colour of the drawing object, respectively.

BufferedImage class is an extension of java.awt.Image found in java.awt.image package, allowing Direct access to all methods of a Image object.

import java.io.*;
import java.awt.*;
import javax.imageio.*;
import java.awt.image.BufferedImage;
public class ImageColorExample
{
           public static void main(String args[]) throws IOException
     {
          File Picture = new File("Photo.jpg");
          BufferedImage JPGPic = ImageIO.read(Picture);
          int clr = JPGPic.getRGB(100,40);
          int Red =(clr & 0x00ff0000)>> 16;
          int Green =(clr & 0x0000ff00)>>8;
          int Blue =clr & 0x000000ff;
          System.out.println("Red Color value ="+Red);
          System.out.println("Green Color value ="+Green);
          System.out.println("Blue Color value ="+Blue);
      }
}

Get Pixel Color BufferedImage

Java Get Image Size Example

By Dinesh Thakur

getWidth and getHeight are predefined abstract methods present in Image class. getWidth method determines the width of an image. getHeight method determines the height of an image. Return type of this two method are int type. Syntax- public abstract int get Width (java.awt.image.    ImageObserver) public abstract int get Height java.awt.image. ImageObserver).

setFont and setColor are predefined abstract methods present in Graphics class. These methods are used to set the font and color of the graphics     context respectively. Syntax-public abstract void setFont (java.awt.Font) public abstract void setColor (java.awt.Color).

 

Here is the Java Example for GetImageSizeExample:

import java.awt.*; 
import java.awt.event.*;
import java.util.Locale;
public class GetImageSizeExample extends Frame
{
         Image image;
         String Picture = "DineshThakur.jpg";
         String Name = "Dinesh Thakur";
         int width,height;
         public GetImageSizeExample()
     {
         addWindowListener(new WindowAdapter()
            {
                 public void windowClosing(WindowEvent e)
                  {
                        System.exit(0);
                   }
            });
     }
             public void paint(Graphics g)
               {
                    Toolkit tool = Toolkit.getDefaultToolkit();
                     image = tool.getImage(Picture);
                     width=image.getWidth(this);
                     height=image.getHeight(this);
                     this.setSize(width+320,height+250);
                     g.drawImage(image,150,120,this);
                     g.setColor(new Color(0,0,180));
                     g.setFont(new Font("Times New Roman",1,12));
                     g.drawString(Name.toUpperCase(Locale.ENGLISH),125,185);
                     g.setFont(new Font("Times new Roman",1,10));
                     g.drawString("My Pic Size: "+width+ "*"+height,135, height+160);
                }
                   public static void main(String args[]) throws Exception
                    {
                       GetImageSizeExample GIS = new GetImageSizeExample();
                       GIS.setVisible(true);
                       GIS.setSize(350,250);
                       GIS.setLocation(200, 100);
                    }
}

find out the image size

Toolkit.getDefaultToolkit().getImage in Java Example

By Dinesh Thakur

addWindowListener method is used to add the windowlistener interface to the window. WindowClosing is a predefined method of WindowListener interface present in java.awt package. exit is a predefined static method present in System class, used to terminate the currently running java. syntax-public static void exit (int status)

Toolkit class is abstract class present in java.awt package. It toolkit is predefined method present in Toolkit class. This method is used to create the object of Toolkit class. Syntax-public static Toolkit getDefaultToolkit ().

getImage is a predefined abstract method present in Toolkit class. Return type of this method is Image class object. Syntax-public abstract Image getImage (java.net. URL)

drawImage and drawString are abstract methods present in Graphics class. These methods are used to draw an image and string respectively. Syntax-public abstract boolean drawImage (Image image, int, int, java. awt. image.ImageObserver) public abstract void drawString (String s, int, int)
setSize is a predefined method present in Frame class , used to set the size of the frame. setVisible is a predefined method present in Frame class, used to make the frame visible. setLocation is a predefined method present in Frame class, used to set the frame at a particular position.

Here is the Java Example for getDefaultToolkitExample:

import java.awt.*; 
import java.awt.event.*;
public class getDefaultToolkitExample extends Frame
{
              Image image;
              String Picture = "DineshThakur.jpg";
              public getDefaultToolkitExample ()
                   {
                       addWindowListener(new WindowAdapter()
                          {
                                public void windowClosing(WindowEvent we)
                                   {
                                        System.exit(0);
                                   }
                           });
                    }
                              public void paint(Graphics g)
                                 {
                                    Toolkit tool = Toolkit.getDefaultToolkit();
                                     image = tool.getImage(Picture);
                                     g.drawImage(image,145,110,this);
                                  
                                  }
                              public static void main(String args []) throws Exception
                                 {
                                          getDefaultToolkitExample image = new getDefaultToolkitExample();
                                          image.setTitle("Toolkit.getDefaultToolkit().getImage Example");
                                          image.setSize(350,250);
                                          image.setVisible(true);
                                          image.setLocation(200,100);
                                        
                                 }
}

Toolkit.getDefaultToolkit().getImage in Java Example

BufferedImage to Image in Java Example

By Dinesh Thakur

JFrame class is a predefined class present in javax.swing package. setLayout method is a predefined method present in JFrame class used to set the layout the frame.  BufferedImage class is a predefined class present in java.awt.image package. getGraphics method is a predefined method present in BufferedImage class. Return type of this method is Graphics class object. Syntax-public Graphics getGraphics ().

setColor is a predefined abstract method of Graphics class present in java.awt package used to set the color of Graphics context. Syntax-public abstract void setColor (Color c) drawOval method is a predefined method of Graphics class present in java.awt package used to draw the oval. Syntax-public abstract void drawOval (int, int, int, int) JLabel class is a predefined class present in javax.swing package. add method is a predefined method present in JFrame class. Here it is used to add the label in the frame. setTitle method is a predefined method present in JFrame class used to set the title of the frame.

Syntax-public void setTitle (String s) setSize method is a predefined method present in JFrame class used to set the size of the frame. syntax- public void setSize (int x, int y).

Here is the Java Example forBufferedImage

import java.awt.*; 
import javax.swing.*;
import java.awt.image.BufferedImage;
class BufferedImageExample
{
                public static void main(String[] args)
        {
                JFrame panel = new JFrame();
                panel.setLayout(new FlowLayout() );
                BufferedImage image=new BufferedImage(400,400, BufferedImage.TYPE_INT_ARGB);
                Graphics G=image.getGraphics();
                G.setColor(Color.blue);
                G.drawOval(140, 25, 120, 50);
                G.dispose();
                JLabel lblOval = new JLabel(new ImageIcon(image));
               panel.add(lblOval);
                panel.setTitle("Graphics");
                panel.setSize(200,150);
                panel.setVisible(true);
        }
}

BufferedImage to Image in Java

Clipboard in Java Swing Example

By Dinesh Thakur

In this Example, JFrame class is a predefined class present in swing package. This class is used to generate a frame and takes string argument. getTooZkit () method is a predefined method of Toolkit class. It returns the system’s default Toolkit object. The default Toolkit is identified by the System property awt.toolkit.

Syntax- public static Toolkit getToolkit () getSystemClipboard () method is a predefined method of Clipboard class. It returns a reference to the system’s clipboard. The clipboard allows Java programs to use cut and paste operations, either internally or as an interface between the program and objects outside of Java. For instance, the following code copies a String from a Java program to the system’s clipboard. Syntax-public abstract Clipboard getSystemClipboard ().JTextArea class is a predefined class present in swing package. This class is used to generate textarea in which user can write something in column and row direction. JButton class is a predefined class present in swing package.

 

Here is the Java Example for Clipboard in Java:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
public class GetClipboard
{
               public static void main(String args[])
          {
                JFrame frame = new JFrame("use Clipboard");
                final Clipboard clipboard=frame.getToolkit().getSystemClipboard();
                final JTextArea area = new JTextArea();
                frame.add(area,BorderLayout.CENTER);
                JButton copy = new JButton("copy");
                copy.addActionListener (new ActionListener()
                      {
                         public void actionPerformed(ActionEvent e)
                           {
                              String selection = area.getSelectedText();
                              StringSelection data = new StringSelection (selection);
                              clipboard.setContents(data,data);
                           }
                      });
                              JButton paste = new JButton("paste");
                 paste.addActionListener(new ActionListener ()
                   {
                       public void actionPerformed(ActionEvent actionEvent)
                        {
                           Transferable clipData= clipboard.getContents (clipboard);
                          try
                              {
                                  if(clipData.isDataFlavorSupported(DataFlavor.stringFlavor))
                                    {
                                        String s= (String)(clipData.getTransferData(DataFlavor.stringFlavor));
                                        area.replaceSelection(s);
                                    }
                              }
                                       catch (Exception ae){}
                        }
                    });
                           JPanel p = new JPanel();
                           p.add(copy);
                           p.add(paste);
                           frame.add(p,BorderLayout.SOUTH);
                           frame.setSize(300,200);
                           frame.setVisible(true);
           }
}

Clipboard in Java Swing Example

Calendar Class in Java Example

By Dinesh Thakur

In this Example, Calendar class is an abstract class present in java.util package. getInstance method is a static method of Calendar class. This method is used to create the object of Calendar class. Return type of this method is Calendar class object. Syntax-public static Calendar getInstance (). get method is a predefined method of Calendar class. It is used to return the value of a given calendar field. Return type of this method is int type. Syntax-public int get (int)

MONTH, YEAR, DATE are predefined constants of Calendar class. Syntax-public static final int MONTH, public static final int YEAR, public static final int DATE add method is a predefined abstract method of Calendar class. It adds or substracts the specified amount of time to the given calendar field. Here we subtract 10 days from the current date. Syntax-public abstract void add (int field, int amount)

 

Here is the Java Example for Calendar Class

import java.util.Calendar; 
public class ShowDateCalendar
{
            public static void main(String[] args)
      {
           Calendar now=Calendar.getInstance();
           System.out.println("Current Date: " +(now.get (Calendar.MONTH)) + "-" + now.get(Calendar.DATE) + "-"+ now.get (Calendar.YEAR));
           now.add(Calendar.DATE,1);
           System.out.println ("Date After One Day: "+ (now.get (Calendar.MONTH)) +"-"+ (now.get (Calendar.DATE) +1) +"-"+ now.get (Calendar.YEAR));
           now=Calendar.getInstance();
           now.add(Calendar.DATE,-10);
           System.out.println ("Date Before 10 Days : " +"-" +(now.get(Calendar.MONTH)) +"-" + (now.get(Calendar.DATE)) + "-" + now.get(Calendar.YEAR));
      }
}

Calendar Class in Java

« Previous Page
Next Page »

Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW