Search This Blog

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, September 2, 2025

Java Math API - 1

 Which of the following is a superclass of java.lang.Math class?

a) System

b) Process

c) Integer

d) Object


Created by Nancy K.A.N.  

@14:52 02-Sept-2025

Tuesday, August 26, 2025

Data type conversion - Java

 An integer variable does not have a fractional component. When a floating point value is assigned to an integer ______________________ happens.

a) Shrinking

b) upcasting

c) nothing

d) truncation


Created by Nancy K.A.N.

@14:42 26-Aug-2025

Friday, August 22, 2025

Java Command Line Arguments

 A Java application can receive arguments from the command line. These arguments can later be processed according to the application requirements. The user can pass these arguments while invoking a Java application:

C:\> java MyApp hello 100 200 300 bye

hello, 100, 200, 300, bye, are the arguments passed to the application MyApp.

When Java launches the application, to which method are these arguments passed?

a) getEnv method

b) getProperties method

c) main method

d) clone method


Created by Nancy K.A.N.

@11:13 22-08-2025

Wednesday, August 20, 2025

Java Runtime

 Which of the following Java classes' objects is responsible for loading classes at runtime?

a) System

b) Runtime

c) ClassLoader

d) Class


Created by: Nancy K.A.N.

@19:41 20-Aug-2025

Wednesday, July 2, 2025

Java Variables - 2

 Which of the following are invalid variable names in Java?

a) !

b) $

c) _$

d) _


Created by Nancy K.A.N.

@23:09 02-Jul-2025

Follow on YouTube

https://kannancy.blogspot.com/

Tuesday, July 1, 2025

Java String API - 1

 Which of the following methods is used to convert a Java String to an array of characters?

a) split()

b) getChars()

c) getBytes()

d) toCharArray()


Created by Nancy K.A.N.

@23:05 01-Jul-2025

Follow on YouTube

https://kannancy.blogspot.com/

Sunday, June 15, 2025

Java Exceptions

 Which of the Following is a Java checked exception?

a) ArithmeticException

b) ArrayIndexOutOfBoundsException

c) FileNotFoundException

d) ClassCastException


Created by Nancy K.A.N.

@12:23 15-Jun-2025

Wednesday, June 11, 2025

Java Collections - 1

 Which of the following is the root interface of Java collections?

a) Collections

b) Collection

c) Abstract Collection

d) Concurrent Collection


Created by Nancy N.

@12:38 11-Jun-2026

Wednesday, April 23, 2025

REST - 1

 Which protocol will you use in a REST service?

a) SOAP

b) JMS

c) HTTP

d) SMTP

e) FTP

Wednesday, December 16, 2015

Enhanced for Loop : Collections and Immutability

Enhanced for loop was added in Java SE 1.5. It can be used with Arrays and collections to iterate item-wise/element-wise. It works like read data of very ancient programming language called BASIC... atleast to me it looks like that... You can define read element of the collection element type and do operations on data. The amazing part is whatever you do to the read element, it does not disturb the original collection, that is data in for loop is immutable...
package test;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.random;
/**
*
* @author nkan
*/
public class EnhancedForLoop {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
for (int i=0;i<5;i++){
intList.add((int) (random() * 100));
}

System.out.println("Added List elements : "+intList);
/* To perfomr element wise operation */
for(int x : intList){
x++;
System.out.println("x = "+x);
}
/* you have incremented x, may be you are thinking that ArrayList : intList has be modified */
System.out.println("List elements now : "+intList);
/* OOPs... it has not changed...But let us conform it once again by using enhanced for loop */
System.out.println("After Updation : incremented element list is : ");
for(int x : intList){
System.out.println("x = "+x);
}
}
}
When I executed this program :
Added List elements : [98, 14, 30, 34, 43]
x = 99
x = 15
x = 31
x = 35
x = 44
List elements now : [98, 14, 30, 34, 43]
After Updation : incremented element list is : 
x = 98
x = 14
x = 30
x = 34
x = 43

Created and posted by Nancy @ 12/17/2015 2:25 am

Friday, October 16, 2015

Understanding mysterious static - 2

Oh! that was interesting, if you tried executing the program in the previous post. For a second may be it gave a food for thought to your mind. Why main is not executing first? Why am i getting output as:

In static block...InterestingStatic1
In main...InterestingStatic1

May be something is happening before main is executing. I must know it. Everything is mystery until understood. So let me take you to another interesting and mysterious scenario :

Here is what you do. Nothing much. Add InterestingStatic1Test class to the project you created yesterday. Let the class InterestingStatic1 be there in the project without any changes.

package teststatic;
public class InterestingStatic1Test {
    static{
        System.out.println("In static block...InterestingStatic1Test");
    }
    public void printSomething(){
        System.out.println("Just printing ... Welcome to Mysteries of Java");
    }
    public static void main(String[] args) {
        System.out.println("In main...InterestingStatic1Test");
        InterestingStatic1Test justObject = new InterestingStatic1Test();
        justObject.printSomething();
        InterestingStatic1 newObject = new InterestingStatic1();
    }
}

Yes, you are right. I am going to ask you to guess the output first and then run the program. Does it match your guess? Why the output is what it is.  wait... there is more to come ... See you...

©K.A.N. Nancy

Thursday, October 15, 2015

Understanding mysterious static - 1

package teststatic;
public class InterestingStatic1 {
    static{
        System.out.println("In static block...InterestingStatic1");
    }
    public static void main(String[] args) {
        System.out.println("In main...InterestingStatic1");
    }
}
What do you think should be the output. Normal understanding is main is executed first by JVM. Run this code. Do you find something unexpected?
More interesting code … tomorrow… let the mystery of static be resolved slowly, so that you enjoy…

©K.A.N. Nancy

Wednesday, October 14, 2015

static in Java - 1

When a static block in a Java class is executed?
     a) When the class is compiled
     b) When the first method in class is executed
     c) When the object is created, but before the constructor is called
     d) When the object is created, and after the constructor is called
     e) When the class is loaded

©K.A.N. Nancy

Tuesday, October 13, 2015

Adding 2 numbers using Java

Let us have fun to add two numbers in variety of ways :

public class FunWithAdd {
   private int num1;
   private int num2;
  public FunWithAdd(int num1, int num2){
       this.num1=num1;
       this.num2=num2;
   }
   public int getNum1(){
       return num1;
   }
    public int getNum2(){
       return num2;
   }
    public void setNum1(int num1){
        this.num1=num1;
    }
    public void setNum2(int num2){
        this.num2=num2;
    }
   int sum(){
       return num1+num2;
   }
   int sum(int n1, int n2){
       return n1+n2;
   }
   int sumWithItr (int n1, int n2){
      int s=n1;
     
      for(int i=1;i<=n2;i++){
          s++;
      }
      return s;
   }
   int sumRecursive(int n1, int n2){
        if (n2 ==0){
            return n1;
        }
        return sumRecursive(++n1,--n2);
      }
   }

Create a class to test variety of sum methods.

public class Add2Nums {
    public static void main(String[] args) {
        /* Summing Locals */
        int num1=25;
        int num2=12;
        System.out.println("sum : "+(num1+num2));
        /* Sum using Object of FunWithAdd*/
        FunWithAdd numsObject= new FunWithAdd(30,60);
        System.out.println("Adding the numbers in Object : "+numsObject.sum());
        System.out.println("Adding the numbers in Object by sending data from outside :"+numsObject.sum(19,20));
        numsObject.setNum1(7);
        numsObject.setNum2(9);
        System.out.println("sum using sumWithItr method : "  +numsObject.sumWithItr(numsObject.getNum1(),numsObject.getNum2()));
         numsObject.setNum1(43);
        numsObject.setNum2(2);
        System.out.println("sum using sumRecursive: "+numsObject.sumRecursive(numsObject.getNum1(),numsObject.getNum2()));
    }
}

Output :
sum : 37
Adding the numbers in Object : 90
Adding the numbers in Object by sending data from outside :39
sum using sumWithItr method : 16
sum using sumRecursive: 45

Change the values and have fun… :)
©Nancy : created at 2:07 am IST

Sunday, June 21, 2015

Interesting Facts about JAVA - 2

Did you know ? (These were later removed from java)
1. All exceptions were unchecked
2. unprotect keyword could be used to avoid signaling asynchronous exceptions

Friday, April 10, 2015

AtomicOperations

Atomic operations are singular ( an operation that cannot be stopped in between). Just like a transaction, it happens completely or does not happen at all. The operations that are atomic :
  1. Read and write for reference variables
  2. Read and write for byte, short, int, char, float, and Boolean
  3. Read and write for all variables declared with the volatile qualifier ( this includes all primitive types)
Operations like increment and decrement look like atomic operations, but there is no guarantee that they are atomic. As any increment operation x++ can be a group of three operations
a)      Temporary copy of x will be created
b)      Temporary copy will be incremented
c)       Newly incremented value will be written back to variable x

Variables of datatype double and long are 64-bit and can be accessed by 2 32-bit operations. During concurrent programming, this can compromise the integrity of data. Java.util.concurrent provides atomic APIs to solve this problem. Let us take a look at an example:

package atomicops;

import java.util.concurrent.atomic.AtomicLong;

/**
 *
 * @author Nancy
 */
public class TestAtomicLong {
    public static void main(String[] args) {
        AtomicLong myLong= new AtomicLong(25);
     
        long x = myLong.getAndAdd(20);
        System.out.println("x ="+x);
        x=myLong.get();
        System.out.println("x ="+x);
     
        x = myLong.addAndGet(30);
        System.out.println("x ="+x);
     
        boolean b = myLong.compareAndSet(75,100);
        System.out.println("b ="+b);
        x=myLong.get();
        System.out.println("x ="+x);
     
        x= myLong.incrementAndGet();
        System.out.println("x="+x);
     
         x= myLong.decrementAndGet();
        System.out.println("x="+x);
    }  
}

Output :
x =25
x =45
x =75
b =true
x =100
x=101
x=100

Other Atomic operation classes are : 

©Nancy
11th April, 2015
2:34 am

Tuesday, March 4, 2014

Which Constructors are called?

public class First {
    public First(){
        super();
        System.out.println("First... No Actually Second");
    }
}

public class Second extends First {
    public Second(){
        super();
        System.out.println("Second...No third");
    }
    public static void main(String[] args) {
        Second second= new Second();
    }
}

Will this code run? Answer to that is YES.

OUTPUT : 

First... No Actually Second
Second...No third

Why highlighted statement super() in First class does not give an error?

As we create an object of Subclass'Second', constructors are called in the order of creation of classes. Second() makes call to First() before it executes the instructions in Second(). First() makes a call to its Super class constructor Object()  which is Universal Super class of all Java Objects.

Saturday, February 22, 2014

Date and Time --- Simple Arithmetic

/* Program to add and subtract days and Hours. It can be applied for other fields of date and time too */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;
import java.util.Calendar;


public class DateTimeUtility {
    public static void main(String[] args) {
        int addDays = 4;
        int subtractDays = 10;
        int addHours=3;
        int subtractHours=26;
     
        Calendar cal = Calendar.getInstance();
        //System.out.println(cal);
        //Current date
        System.out.println("Today's date : " + (cal.get(Calendar.MONTH) + 1) +
                "/" + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR));
   
        //Current Time
        System.out.println("Current Time  : " + (cal.get(Calendar.HOUR) ) +
                ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));

        //Adding days
        cal.add(Calendar.DATE, addDays);
        System.out.println("Date (after): " + (cal.get(Calendar.MONTH) + 1) +
                "/" + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR));
        cal = Calendar.getInstance();

        //subtracting days
        cal.add(Calendar.DATE, -subtractDays);
        System.out.println("Date (before): " + (cal.get(Calendar.MONTH) + 1) +
               "/" + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR));

       //Adding Hours
        cal.add(Calendar.HOUR, addHours);
        System.out.println("New Time after adding " + addHours +" Hours "+
                cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE) +
                ":" + cal.get(Calendar.SECOND));
        cal=Calendar.getInstance();

       //Subtracting Hours
        cal.add(Calendar.HOUR, -subtractHours);
        System.out.println("Time before " + subtractHours+" Hours "+
                (cal.get(Calendar.HOUR) ) + ":" + cal.get(Calendar.MINUTE) +
                ":" + cal.get(Calendar.SECOND));
    }
}

OUTPUT :

Today's date : 2/22/2014
Current Time  : 6:22:6
Date (after): 2/26/2014
Date (before): 2/12/2014
New Time after adding 3 Hours 9:22:6
Time before 26 Hours 4:22:6

Thursday, January 30, 2014

Something about Overloading...

Overloading allows to use same name of method for multiple methods provided signatures are different. Signatures can be different in number, in type or in order. Example below shows.

public class OverloadDemo {
    public int add(int x, int y){
        return x+y;
    }
    public int add(int x, int y, int z){
        return x+y+z;
    }

    public double add(int x, double y){
        return x+y;
    }

    public double add(double x, int y){
        return x+y;
    }

    public static void main(String[] args) {
        OverloadDemo obj = new OverloadDemo();

        System.out.println(obj.add(10,20));
        System.out.println(obj.add(10,20,56));
        System.out.println(obj.add(10,20.9));
        System.out.println(obj.add(10.7,20));
    }

}

Output :

run:
30
86
30.9
30.7

It is simple. It is a user-friendly feature of Java and all Object-Oriented Programming languages.

Here is a small twist. See the code ...

public class AnotherOverload {
 
    int add (int x, int y){
        System.out.println("Int Overload");
        return x+y;
    }
    int add (short x, short y){
        System.out.println("Short Overload");
        return x+y;
    }
    long add(long x, long y){
        System.out.println("Long overload");
        return x+y;
    }
    double add(double x, double y){
        System.out.println("double overload");
        return x+y;
    }
    float add(float x, float y){
        System.out.println("double overload");
        return x+y;
    }
    public static void main(String[] args) {
        AnotherOverload ob = new AnotherOverload();
        System.out.println("sum of 10 + 20 is "+ob.add(10,20));
        System.out.println("sum of 10.1 + 20.1 is "+ob.add(10.1,20.2));
    }
}
Output:

Int Overload
sum of 10 + 20 is 30
double overload
sum of 10.1 + 20.1 is 30.299999999999997

There are two Questions over here :

10 and 20 are short type values according to the range, rather I can say it falls in the range of byte. But the method is called with an int parameters. Likewise 10.1 and 20.1 are float values but the call is for double. All non-real numeric literals by default are int and all real literals are double.

Here is another interesting scenario...

class IntOverload {
public static void main(String args[]) {
int x=10,y=20;
                short a=5, b=7;

IntOverload ob = new IntOverload();
System.out.println(ob.add(x,y));
        System.out.println(ob.add(a,b));
        
}
        
        short add(short a, short b){
            System.out.println("Short");
            return a+b;
        }

long add(long a, long b){
System.out.println("long");
return a+b;
}

float add(float a, float b){
System.out.println("float");
return a+b;
}

double add(double a, double b){
System.out.println("double");
return a+b;
}
}

This code does not compile and give an error :

When add method is called with explicit short type, it gives compile time error "Required :short, found:int".

All integer type numerics are promoted to int type at the time of computation. So the solution can be achieved by changing the method code. We use explicit cast... just a word of caution when overloading...

 short add(short a, short b){
            System.out.println("Short");
            return (short)(a+b);
        }

Enjoy coding... :)

Monday, January 27, 2014

Understanding final keyword part - 2 Just a small tidbit... 'njoy java

Now, here is an interesting scenario for you, a simple mind excercise.

Java understands final lil different from constant. Say I create a final array with the following code.

public class FinalArray1 {
    private final int[] arr = new int[5];
   
    public FinalArray1(){
        for(int i=0; i<arr.length;i++){
            arr[i]= (int)(Math.random()*25);
        }
    }
    public void printArray(){
        System.out.print("[ ");
        for(int i=0;i<arr.length;i++){
             System.out.print(arr[i]+" ");
        }
        System.out.println("]");
    }
    public void setNthElement(int index,int value){
        if(index<arr.length){
            arr[index]=value;
        }
    }
}

To test whether array is final or not, here is a Tester class:

public class TestFinalArray1 {
    public static void main(String[] args) {
        FinalArray1 arrayObj = new FinalArray1();
        arrayObj.printArray();
        arrayObj.setNthElement(2, (int)(Math.random()*100));
        arrayObj.printArray();
    }
}

On execution, we can see the data of 3rd element is changed.

run:
[ 11 15 11 10 11 ]
[ 11 15 30 10 11 ]
BUILD SUCCESSFUL (total time: 1 second)

So in what sense is it constant? let us take a look at this. We add newArray(int size) method to FinalArray1 class. 

public void newArray(int size){
        arr= new int[size];
    }



we can see an error on compile : "cannot assign a value to final variable arr". arr array reference variable is final and not the array elements.