[go: up one dir, main page]

0% found this document useful (0 votes)
9 views24 pages

JAVA - Long Answer

The document discusses Java programming concepts including command-line arguments, type casting, literals, overloaded constructors, and method overriding. It explains how to pass and access command-line arguments, differentiate between implicit and explicit type casting, and provides examples of various types of literals. Additionally, it covers the concept of overloaded constructors for flexible object creation and the differences between method overriding and method overloading.

Uploaded by

lakshmimahaa999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views24 pages

JAVA - Long Answer

The document discusses Java programming concepts including command-line arguments, type casting, literals, overloaded constructors, and method overriding. It explains how to pass and access command-line arguments, differentiate between implicit and explicit type casting, and provides examples of various types of literals. Additionally, it covers the concept of overloaded constructors for flexible object creation and the differences between method overriding and method overloading.

Uploaded by

lakshmimahaa999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT - I

1. How can command-line arguments be passed to a Java program? Provide an example


of how they can be accessed within a program.

Java Command Line Arguments


The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be
used as an input.

So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java program,
you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

Example of command-line argument that prints all


the values
In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.
class A

{ public static void main(String args[])

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

System.out.println(args[i]);

compile by > javac A.java

run by > java A sonoo jaiswal 1 3 abc


Output: sonoo/
jaiswal
1
3
abc

4.What is type casting? Differentiate between implicit and explicit type casting with
examples.

Type Casting in Java


In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically. The automatic conversion is done by the compiler and
manual conversion performed by the programmer. In this section, we will discuss type
casting and its types with proper examples.

Type casting
Convert a value from one data type to another data type is known as type casting.

Types of Type Casting


There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting

Widening Type Casting


Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:

o Both data types must be compatible with each other.


o The target type must be larger than the source type.
1. byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's
see an example.
WideningTypeCastingExample.java

public class WideningTypeCastingExample

public static void main(String[] args)

int x = 7;

//automatically converts the integer type into long type

long y = x;

//automatically converts the long type into float type

float z = y;

System.out.println("Before conversion, int value "+x);

System.out.println("After conversion, long value "+y);

System.out.println("After conversion, float value "+z);

Output

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0

In the above example, we have taken a variable x and converted it into a long type. After that,
the long type is converted into the float type.

Narrowing Type Casting


Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If we do
not perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

Let's see an example of narrowing type casting.

Advertisement

In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into int
type.

NarrowingTypeCastingExample.java

public class NarrowingTypeCastingExample


{

public static void main(String args[])

double d = 166.66;

//converting double data type into long data type

long l = (long)d;

//converting long data type into int data type

int i = (int)l;

System.out.println("Before conversion: "+d);

//fractional part lost

System.out.println("After conversion into long type: "+l);

//fractional part lost

System.out.println("After conversion into int type: "+i);

Output

Before conversion: 166.66


After conversion into long type: 166
After conversion into int type: 166

6.What are literal constants in Java? Provide examples.

Literals in Java
In Java, literal is a notation that represents a fixed value in the source code. In lexical analysis,
literals of a given type are generally known as tokens. In this section, we will discuss the
term literals in Java.

Literals
In Java, literals are the constant values that appear directly in the program. It can be assigned
directly to a variable. Java has various types of literals. The following figure represents a literal.
Types of Literals in Java
There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:

Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a positive
(+) or negative (-) Note that between numbers commas and non-digit characters are not permitted. For
example, 5678, +657, -89, etc.

int decVal = 26;

Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For example, 045,
026,

int octVal = 067;

Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as hexadecimal integers. It may


also include a character from a to f or A to F that represents numbers from 10 to 15, respectively. For
example, 0xd, 0xf,

int hexVal = 0x1a;

Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java
SE 7 and later). Prefix 0b represents the Binary system. For example, 0b11010.

int binVal = 0b11010;

Real Literals
The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.

Backslash Literals
Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:
\n: It is used for a new line

\t: It is used for horizontal tab

\b: It is used for blank space

\v: It is used for vertical tab

\a: It is used for a small beep

\r: It is used for carriage return

\': It is used for a single quote

\": It is used for double quotes

Character Literals
A character literal is expressed as a character or an escape sequence, enclosed in
a single quote ('') mark. It is always a type of char. For example, 'a', '%', '\u000d', etc.

String Literals
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It
may be alphabet, numbers, special characters, blank space, etc. For example, "Jack",
"12345", "\n", etc.

Floating Point Literals


The vales that contain decimal are floating literals. In Java, float and double primitive types fall
into floating-point literals. Keep in mind while dealing with floating-point literals.

Advertisement

o Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It is a 32-bit
float literal.
o Floating-point literals for double type end with D or d. It is optional to write D or d. For
example, 6d, 8.354D, etc. It is a 64-bit double literal.
o It can also be represented in the form of the exponent.
Floating:

float length = 155.4f;

Decimal:

double interest = 99658.445;

Decimal in Exponent form:


Advertisement

double val= 1.234e2;

Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0 and 1. For
example, true, 0, etc.

boolean isEven = true;


Null Literals
Null literal is often used in programs as a marker to indicate that reference type object is unavailable.
The value null may be assigned to any variable, except variables of primitive types.

String stuName = null;

Student age = null;

Class Literals
Advertisement

Class literal formed by taking a type name and appending .class extension. For
example, Scanner.class. It refers to the object (of type Class) that represents the type itself.

class classType = Scanner.class;

Invalid Literals
There is some invalid declaration of literals.

float g = 6_.674f;

float g = 6._674F;

long phoneNumber = 99_00_99_00_99_L;

int x = 77_;

int y = 0_x76;

int z = 0X_12;

int z = 0X12_;

Restrictions to Use Underscore (_)


o It can be used at the beginning, at the end, and in-between of a number.
o It can be adjacent to a decimal point in a floating-point literal.
o Also, can be used prior to an F or L suffix.
o In positions where a string of digits is expected.

Why use literals?


To avoid defining the constant somewhere and making up a label for it. Instead, to write the
value of a constant operand as a part of the instruction.

Advertisement

How to use literals?


A literal in Java can be identified with the prefix =, followed by a specific value.

Let's create a Java program and use above discussed literals.

LiteralsExample.java

public class LiteralsExample

{
public static void main(String args[])

int count = 987;

float floatVal = 4534.99f;

double cost = 19765.567;

int hexaVal = 0x7e4;

int binary = 0b11010;

char alpha = 'p';

String str = "Java";

boolean boolVal = true;

int octalVal = 067;

String stuName = null;

char ch1 = '\u0021';

char ch2 = 1456;

System.out.println(count);

System.out.println(floatVal);

System.out.println(cost);

System.out.println(hexaVal);

System.out.println(binary);

System.out.println(alpha);

System.out.println(str);

System.out.println(boolVal);

System.out.println(octalVal);

System.out.println(stuName);

System.out.println(ch1);

System.out.println("\t" +"backslash literal");

System.out.println(ch2);

Output:
987
4534.99
19765.567
2020
26
p
Java
true
55
null
!
backslash literal
?

UNIT -II

7.Explain the concept of overloaded constructors. Provide an example where multiple


constructors are used in a class.

In Java, a constructor is said to be overloaded when a class has more than one constructor, each
differing in the number or type of parameters. Overloaded constructors allow the creation of objects
in different ways, providing flexibility based on the needs of the program. Each constructor performs
a specific initialization based on the passed arguments.

Example:
class Student
{
String name;
int age;
String department;

// Constructor 1: No parameters
public Student()
{
name = "Unknown";
age = 0;
department = "Not assigned";
}

// Constructor 2: One parameter


public Student(String n)
{
name = n;
age = 0;
department = "Not assigned";
}

// Constructor 3: Two parameters


public Student(String n, int a)
{
name = n;
age = a;
department = "Not assigned";
}

// Constructor 4: Three parameters


public Student(String n, int a, String dept)
{
name = n;
age = a;
department = dept;
}

// Method to display student details


public void display()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Department: " + department);
}
}

public class Main


{
public static void main(String[] args)
{
// Creating objects using different constructors
Student student1 = new Student();
Student student2 = new Student("Alice");
Student student3 = new Student("Bob", 20);
Student student4 = new Student("Charlie", 22, "Computer Science");

// Displaying details of each student


student1.display();
System.out.println();
student2.display();
System.out.println();
student3.display();
System.out.println();
student4.display();
}
}

Output:
Name: Unknown
Age: 0
Department: Not assigned

Name: Alice
Age: 0
Department: Not assigned

Name: Bob
Age: 20
Department: Not assigned

Name: Charlie
Age: 22
Department: Computer Science

Explanation:

1. Constructor 1 (No parameters): Initializes default values.


2. Constructor 2 (One parameter): Allows the user to specify the name.
3. Constructor 3 (Two parameters): Allows the user to specify the name and age.
4. Constructor 4 (Three parameters): Allows the user to specify the name, age, and department.

9.What is method overriding in Java? How does it differ from method overloading?

Method Overriding in Java


1. Understanding the problem without method overriding
2. Can we override the static method
3. Method overloading vs. method overriding

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding


Let's understand the problem that we may face in the program if we don't use method
overriding.

//Java Program to demonstrate why we need method overriding

//Here, we are calling the method of parent class with child

//class object.

//Creating a parent class

class Vehicle{

void run(){System.out.println("Vehicle is running");}

//Creating a child class

class Bike extends Vehicle{

public static void main(String args[]){

//creating an instance of child class

Bike obj = new Bike();

//calling the method with child class instance

obj.run();

}
Output:

Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the same,
and there is IS-A relationship between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding

//Creating a parent class.

class Vehicle{

//defining a method

void run(){System.out.println("Vehicle is running");}

//Creating a child class

class Bike2 extends Vehicle{

//defining the same method as in the parent class

void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){

Bike2 obj = new Bike2();//creating object

obj.run();//calling method

Output:

Bike is running safely

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7%, and 9% rate of interest.

Java method overriding is mostly used in Runtime Polymorphism which we


will learn in next pages.

//Java Program to demonstrate the real scenario of Java Method Overriding

//where three classes are overriding the method of a parent class.

//Creating a parent class.

class Bank{

int getRateOfInterest(){return 0;}

//Creating child classes.

class SBI extends Bank{

int getRateOfInterest(){return 8;}

class ICICI extends Bank{

int getRateOfInterest(){return 7;}

class AXIS extends Bank{

int getRateOfInterest(){return 9;}

//Test class to create objects and call the methods

class Test2{

public static void main(String args[]){

SBI s=new SBI();


ICICI i=new ICICI();

AXIS a=new AXIS();

System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());

System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());

System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

2. What is the this keyword in Java? Explain its significance with examples.

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

Usage of Java this keyword


Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1) this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:

class Student{

int rollno;

String name;

float fee;

Student(int rollno,String name,float fee){

rollno=rollno;

name=name;

fee=fee;

void display(){System.out.println(rollno+" "+name+" "+fee);}

class TestThis1{

public static void main(String args[]){

Student s1=new Student(111,"ankit",5000f);

Student s2=new Student(112,"sumit",6000f);

s1.display();

s2.display();

}}

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


class Student

int rollno;

String name;

float fee;

Student(int rollno,String name,float fee)


{

this.rollno=rollno;

this.name=name;

this.fee=fee;

void display()

System.out.println(rollno+" "+name+" "+fee);}

class TestThis2

public static void main(String args[])

Student s1=new Student(111,"ankit",5000f);

Student s2=new Student(112,"sumit",6000f);

s1.display();

s2.display();

Output:

111 ankit 5000.0


112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:

Program where this keyword is not required


class Student

int rollno;

String name;

float fee;

Student(int r,String n,float f)


{

rollno=r;

name=n;

fee=f;

void display(){System.out.println(rollno+" "+name+" "+fee);}

class TestThis3

public static void main(String args[])

Student s1=new Student(111,"ankit",5000f);

Student s2=new Student(112,"sumit",6000f);

s1.display();

s2.display();

Output:

111 ankit 5000.0


112 sumit 6000.0

It is better approach to use meaningful names for variables. So we use same


name for instance variables and parameters in real time, and always use this
keyword.

2) this: to invoke current class method


You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example
class A

void m(){System.out.println("hello m");}

void n()

System.out.println("hello n");

//m();//same as this.m()

this.m();

class TestThis4{

public static void main(String args[]){

A a=new A();

a.n();

}}

Output:

hello n
hello m

3) this() : to invoke current class constructor


The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:


class A{

A(){System.out.println("hello a");}

A(int x){

this();

System.out.println(x);

class TestThis5{

public static void main(String args[]){

A a=new A(10);

}}

Output:

hello a
10

Calling parameterized constructor from default constructor:

class A{

A(){

this(5);

System.out.println("hello a");

A(int x){

System.out.println(x);

class TestThis6{

public static void main(String args[]){

A a=new A();

}}

Output:
5
hello a

Real usage of this() constructor call


The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this keyword.

class Student{

int rollno;

String name,course;

float fee;

Student(int rollno,String name,String course){

this.rollno=rollno;

this.name=name;

this.course=course;

Student(int rollno,String name,String course,float fee){

this(rollno,name,course);//reusing constructor

this.fee=fee;

void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}

class TestThis7{

public static void main(String args[]){

Student s1=new Student(111,"ankit","java");

Student s2=new Student(112,"sumit","java",6000f);

s1.display();

s2.display();

}}

Output:

111 ankit java 0.0


112 sumit java 6000.0

Rule: Call to this() must be the first statement in constructor.

class Student{

int rollno;

String name,course;

float fee;

Student(int rollno,String name,String course){

this.rollno=rollno;

this.name=name;

this.course=course;

Student(int rollno,String name,String course,float fee){

this.fee=fee;

this(rollno,name,course);//C.T.Error

void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}

class TestThis8{

public static void main(String args[]){

Student s1=new Student(111,"ankit","java");

Student s2=new Student(112,"sumit","java",6000f);

s1.display();

s2.display();

}}

Output:

Compile Time Error: Call to this must be first statement in constructor

4) this: to pass as an argument in the method


The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:

class S2{

void m(S2 obj){

System.out.println("method is invoked");

void p(){

m(this);

public static void main(String args[]){

S2 s1 = new S2();

s1.p();

Output:

method is invoked

Application of this that can be passed as an argument:


In event handling (or) in a situation where we have to provide reference of a class to another
one. It is used to reuse one object in many methods.

5) this: to pass as argument in the constructor call


We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:

class B{

A4 obj;

B(A4 obj){

this.obj=obj;

void display(){

System.out.println(obj.data);//using data member of A4 class

}
class A4

int data=10;

A4(){

B b=new B(this);

b.display();

public static void main(String args[]){

A4 a=new A4();

Output:10

6) this keyword can be used to return current class instance


We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


return_type method_name()

return this;

Example of this keyword that you return as a


statement from the method
class A{

A getA(){

return this;

void msg(){System.out.println("Hello java");}

}
class Test1{

public static void main(String args[]){

new A().getA().msg();

Output:

Hello java

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this program, we
are printing the reference variable and this, output of both variables are same.

class A5{

void m(){

System.out.println(this);//prints same reference ID

public static void main(String args[]){

A5 obj=new A5();

System.out.println(obj);//prints the reference ID

obj.m();

Output:

A5@22b3ea59
A5@22b3ea59

You might also like