Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
66 views

Basic Syntactical Constructs in Java

This document discusses basic syntactical constructs in Java programming. It provides examples of: 1) Features of Java such as being object-oriented, compiled and interpreted, secure, robust, architecture-neutral, platform independent, distributed, and multithreaded. 2) Why Java is platform independent due to use of bytecode that is executed by the Java Virtual Machine (JVM) and is not specific to any machine. 3) Definitions of the JVM and bytecode, with bytecode being an intermediate compiled format that is platform independent. 4) Examples of Java programs demonstrating classes, objects, methods, variables and their scopes, and basic programming constructs.

Uploaded by

Amaan Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Basic Syntactical Constructs in Java

This document discusses basic syntactical constructs in Java programming. It provides examples of: 1) Features of Java such as being object-oriented, compiled and interpreted, secure, robust, architecture-neutral, platform independent, distributed, and multithreaded. 2) Why Java is platform independent due to use of bytecode that is executed by the Java Virtual Machine (JVM) and is not specific to any machine. 3) Definitions of the JVM and bytecode, with bytecode being an intermediate compiled format that is platform independent. 4) Examples of Java programs demonstrating classes, objects, methods, variables and their scopes, and basic programming constructs.

Uploaded by

Amaan Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

BASIC SYNTACTICAL Java Programming

CONSTRUCTS IN JAVA
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

1) State and explain any four features of java?


(Summer-17) 4 marks
a) Java is an object-oriented language: - It follows all the
principles of object-oriented programming namely
inheritance, polymorphism and abstraction. Multiple
inheritance is possible with the concept of interface
b) Java is both compiled and interpreted: - Most of the
programming languages either uses a compiler or an
interpreter. Java programs are to be compiled to get an
intermediate byte code (a .class file) and then interpreted
making it more secure and platform independent
c) Java is secure:
I. Java does not use pointer.
II. Java programs run inside a virtual machine
III. Classloader adds security by separating the package
for the classes of the local file system from those that
are imported from network sources
IV. Bytecode Verifier checks the code fragments for illegal
code that can violate access right to objects
V. Security Manager determines what resources a class
can access such as reading and writing to the local
disk
d) Robust: Java uses strong memory management. The lack of
pointers avoids security problem. There is automatic garbage
collection in java. There is exception handling and type
checking mechanism in java
e) Architecture-neutral: There is no implementation dependent
features e.g., size of primitive types is fixed
f) Platform independent and Portable: java byte code can be
carried to any platform
g) Distributed: Distributed applications can be created in java.
RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any
machine on the internet
h) Multithreaded: A thread is like a separate program, executing
concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

memory for each thread. It shares a common memory area.


Threads are important for multi-media, Web applications etc

2) Why java became platform independent language?


(Winter 17) 4 marks
Java is a platform independent language. This is possible because
when a java program is compiled, an intermediate code called the
byte code is obtained rather than the machine code. Byte code is a
highly optimized set of instructions designed to be executed by the
JVM which is the interpreter for the byte code. Byte code is not a
machine specific code. Byte code is a universal code and can be
moved anywhere to any platform. JVM is a virtual machine which
exists inside the computer memory and is a simulated computer
within a computer which does all the functions of a computer. Only
the JVM needs to be implemented for each platform. Although the
details of the JVM will defer from platform to platform, all interpret
the same byte codes.

Process of converting byte code into machine code


BASIC SYNTACTICAL CONSTRUCTS IN JAVA

3) What is JVM? What is byte code? (Summer 15) 4 marks

JVM is the Java Virtual Machine


The java compiler compiles produces an intermediate code known
as byte code for the java virtual machine, which exists only in the
computer memory It is a simulated computer within the computer
and does all the major functions of a real computer

Virtual machine code is not machine specific Machine specific


code is generated by Java Interpreter by acting as an intermediary
between the virtual machine and the real machine. Interpreter is
written for each type of machine.

Byte code: Bytecode is the compiled format for Java programs.


Once a Java program has been converted to bytecode, it can be
transferred across a network and executed by Java Virtual
Machine (JVM). A Bytecode file generally has a .class extension

4) What is bytecode? Explain any two tools available in jdk?


(Winter 15) 4 marks
Byte code: Bytecode in Java is an intermediate code generated
by the compiler such as Sun’s javac, that is executed by JVM.
Bytecode is compiled format of Java programs ithas a .class
extension.
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

5) Define jdk. List the tools available in jdk? Explain any one?
(Summer 15) 4 marks
Definition: A Java Development Kit (JDK) is a collection of tools
which are used for developing, designing, debugging, executing
and running java programs.
Tools of JDK.
Java
Javap
Javah
Javadoc
jdb
appletviewer
javac
a) Java Compiler – it is used to translate java source code to
byte code files that the interpreter can understand

6) Define a class item having data member code and price.


Accept data for one object and display it. (Summer 16) 4
marks
import java.io.*;
class Item_details
{
int code;
float price;
Item_details()
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

{
code=0;
price=0;
}
Item_details(int e,float p)
{
code=e;
price=p;
}
void putdata()
{
System.out.println("Code of item :"+code);
System.out.println("Price of item:"+price);
}
public static void main(String args[]) throws IOException
{
intco;floatpr;
BufferedReaderbr=new BufferedReader (new
InputStreamReader(System.in));
System.out.println("enter code and price of item");
co=Integer.parseInt(br.readLine());
pr=Float.parseFloat(br.readLine());
Item_detailsobj=new Item_details(co,pr);
obj.putdata();
}
}

7) Write a program to create a class account having variable


accno, accname and balance. Define deposite() and
withdraw() methods. Create one object of class and perform
the operation. (Winter 16) 8 marks
import java.io.*;
class Account
{
int accno;
String accname;
double balance, new_bal;
Account(int accno, String accname, double balance)
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

{
this.accno = accno;
this.accname = accname;
this.balance = balance;
}
void deposite(double deposit_amount)
{
balance = balance+deposit_amount;
System.out.println("Your new available balance is"+balance);
}
void withdraw(double amount)
{
if(balance > amount)
{
balance = balance-amount;
System.out.println("Your current balance"+balance);
}
else if( balance == amount)
{
System.out.println("Your current balance is "+balance+". Your
minimum balance should be 1000. Hence cannot withdraw.");
}
else
{
System.out.println("Insufficient balance");
}
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
Account a;
double amount, bal;
try
{
System.out.println("Enter the account name account number and
balance");
String a_name = bin.readLine();
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

int a_no = Integer.parseInt(bin.readLine());


bal = Double.parseDouble(bin.readLine());
a = new Account(a_no, a_name, bal);
System.out.println("Enter\n 1 for depositing \n 2 for withdrawal");
int option = Integer.parseInt(bin.readLine());
switch(option)
{
case 1:
System.out.println("Enter the amount to deposite");
amount = Double.parseDouble(bin.readLine());
a.deposite(amount);
break;
case 2:
System.out.println("Enter the amount to withdraw");
amount = Double.parseDouble(bin.readLine());
a.withdraw(amount);
break;
default:
System.out.println("Enter a valid option");
break;
}
} catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}

8) State and explain scope of variable with example.


(Summer 18) 4 marks

Scope of Variable:
a) We can declare variables within any block
b) One block equal to one new scope in Java thus each time
you start a new block, you are creating a new scope.
c) A scope determines what objects are visible to other parts of
your program. It also determines the lifetime of those objects.
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

Program:

a) n1 is declared in main block thus it is accessible in main


block.
b) N2 is declared in if block thus it is only accessible inside if
block
c) Any attempt to access it outside block will cause compilation
error.
d) Nested Block can have access to its outmost block.
e) If block is written inside main block thus all the variables
declared inside main block are accessible in if block

9) What is scope of variable? Give example of class variable,


instance variable and local variable. (Winter 16) 6 marks
The scope of a variable defines the section of the code in which
the variable is visible. The variables can be class variable which is
associated with the class and is shared with all the instances of the
class or an instance variable which is declared in a class and each
instance has a separate copy or a local variable which is defined in
a block or a method. As a general rule, variables that are defined
within a block are not accessible outside that block. The lifetime of
a variable refers to how long the variable exists before it is
destroyed.
E.g.:
class VariableTypes
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

{
static int a = 0; //class variable
int b = 0; // instance variable
VariableTypes()
{
a++;
b++;
int c = 0; //local variable
c++;
System.out.println("In constructor printing a: "+a);//will be accessed
System.out.println("In constructor printing b: "+b);//will be accessed
System.out.println("In constructor printing c: "+c);//will be accessed
}
public static void main(String ar[])
{
VariableTypes s = new VariableTypes();
VariableTypes s1 = new VariableTypes();
VariableTypes s2 = new VariableTypes();
System.out.println("in main printing a: "+VariableTypes.a);//will be
accessed
System.out.println("in main printing b: "+s.b);//will be accessed
System.out.println("in main printing c "+s.c);//will not be accessed
because this is a local variable declared in constructor
}
}

10) What is type casting? Explain and its types with proper
syntax and example. (Summer 18) 4 marks
Assigning a value of one type to a variable of another type is
known as Type Casting
There are 2 types of type casting
a) Widening or Implicit type casting
b) Narrowing or Explicit type casting
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

Implicitly Type casting take place when


a) The two types are compatible
b) The target type is larger than the source type
Program:
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

11) Write all primitive data types available in java with their
storage sizes in bytes. (Summer 17) 4 marks

12) Write a simple java program to illustrate use of


mathematical function.
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

// return the maximum of two numbers


System.out.println("Maximum number of x and y is: "
+Math.max(x, y));

// return the square root of y


System.out.println("Square root of y is: " + Math.sqrt(y));

//returns 28 power of 4 i.e. 28*28*28*28


System.out.println("Power of x and y is: " + Math.pow(x, y));

// return the logarithm of given value


System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));

// return the logarithm of given value when base is 10


System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));

// return the log of x + 1


System.out.println("log1p of x is: " +Math.log1p(x));

// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));

// return (a power of 2)-1


System.out.println("expm1 of a is: " +Math.expm1(x));
}
}

13) Describe any two relational and any two logical


operators in java with example. (summer 16) 4 marks
Relational Operators: When comparison of two quantities is
performed depending on their relation, certain decisions are made.
Java supports six relational operators as shown in table.
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

Program demonstrating Relational Operators


class relational
{
public static void main(String args[])
{
int i=37;
int j=42;
System.out.println(“i>j”+(i>j)): //false
System.out.println(“I<j”+(i<j)); //true
System.out.println(“i>=j”+(i>=j)); //false
System.out.println(“i<=j”+(I<=j)); // true
System.out.println(“i==j”+(i==j)); // false
System.out.println(“i!=j”+(i!=j)); //true
}
}

Logical Operators: Logical operators are used when we want to


form compound conditions by combining two or more relations.
Java has three logical operators as shown in table:

Program demonstrating logical Operators


class Log
{
public static void main(String args[])
{
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

boolean A=true;
boolean B=false;
System.out.println(“A\B”+(a|B)); //true
System.out.println(“A&B”+(A&B)); // false
System.out.println(“!A”+(!A)); // false
System.out.println(“A^B”+(A^B)); // true
System.out.println(“(A|B)&A”+((A|B)&A)); // true
}
}

14) Explain any two relational operators in java with


example. (Summer 17) 4 marks
The relational operators in java are:
< - This operator is used to check the inequality of two
expressions. It returns true if the first expression is less than the
second expression else returns false.
if(Exp1< exp2) {
do this
} else {
do this
}

>-This operator is also used to check the inequality of two


expressions. It returns true
if the first expression is greater than the second one else returns
false.
if(Exp1> exp2) {
do this
} else {
do this
}

<=- This operator returns true if the first expression is less than or
equal to the second expression else returns false.
if(Exp1< =exp2) {
do this
} else {
do this
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

>=-This operator returns true if the first expression is greater than


or equal to the second expression else returns false.
if(Exp1>= exp2) {
do this
} else {
do this
}

= =-This operator returns true if the values of both the expressions


are equal else returns false.
if(Exp1= = exp2) {
do this
} else {
do this
}

!= - This operator returns true if the values of both the expressions


are not equal else returns false.
if(Exp1!= exp2) {
do this
} else {
do this
}

Example:
class RelationalOps {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

15) (?:) What this operator is called? Explain with suitable


example. (Summer 15, winter 15) 4 marks
a) “?:” is called as conditional operator or ternary operator.
b) It can be used to check condition in one line, instead of
writing if…else statement.
c) Its format is (condtion ? true case : false case)
d) Example
int a,b;
a=10;
b=(a>5? 12 : 20);
Here b= 12 as a is 10 and condition is true. If value of a is
changed to 15 then b will have value as 20

16) Explain any two bit-wise operators with example.


(Winter 15) 4 marks
a) Bitwise NOT (~): called bitwise complement, the unary NOT
operator, inverts all of the bits of its operand.
e.g~ 0111 (decimal 7) = 1000 (decimal 8)

b) Bitwise AND ( & ): the AND operator, &, produce a 1 bit if


both operands are also 1, A zero is produced in all the
cases.
e.g0101 (decimal 5) &0011 (decimal 3) = 0001 (decimal 1)

c) Bitwise OR ( | ) : the OR operator, | , combines bits such that


if either of the bits in the operand is a 1, then the resultant bit
is a 1
e.g0101 (decimal 5) |0011 (decimal 3) = 0111 (decimal 7)

d) Bitwise XOR ( ^ ): the XOR operator, ^, combines bits such


that if exactly one operand is 1, then the result is 1.
Otherwise, result is zero.
e.g0101 (decimal 5) ^ 0011 (decimal 3) = 0110 (decimal 6)
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

e) The Left Shift (<<): the left shift operator, <<, shifts all of the
bits in a value “to the left a specified number of times
specified by num”
General form: value <<num
e.g. x << 2 (x=12)
0000 1100 << 2 = 0011 0000 (decimal 48)

f) The Right Shift (>>): the right shift operator, >>, shifts all of
the bits in a value “to the right a specified number of times
specified by num”
General form: value >>num.
e.g. x>> 2 (x=32)
0010 0000 >> 2 = 0000 1000 (decimal 8)

g) Unsigned Right Shift (>>>) : >>> always shifts zeros into


high order bit.
e.g. int a= -1
a=a>>>24

11111111 11111111 11111111 11111111 (-1 in binary as


int) >>> 24

00000000 00000000 00000000 11111111(255 in binary as


an int)

h) Bitwise Operators Compound Assignments: All of the above


binary bitwise operators have a compound form similar to
that of the algebraic operators, which combines the
assignment with the bitwise operation. These two statements
are equivalent.
e.g.a = a >>4 ;
a >> = 4;

17) Explain following bit-wise operators with an example.


Left shift operator and right shift operator
(Summer 18) 4 marks
a) The Left Shift (<<): the left shift operator, <<, shifts all of the
bits in a “value” to the left a specified number of times
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

specified by “num”
General form : value <<num
e.g. x << 2 (x=12)
0000 1100 << 2
= 0011 0000 (decimal 48)

b) The Right Shift (>>): the right shift operator, >>, shifts all of
the bits in a “value” to the right a specified number of times
specified by “num”
General form: value >>num
e.g. x>> 2 (x=32)
0010 0000 >> 2
= 0000 1000 (decimal 8)

18) In what ways does a switch statement differ from a if


statement (Winter 16) 4 marks
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

19) Define a class having one 3 digit number, num as data


member, initialize and display reverse of that number
(Summer 15,16) 4 marks
class reverse
{
public static void main(String args[])
{
int num = 253;
int q,r;
for (int I = 0; i<3; i++)
{
q = num / 10;
r = num % 10;
System.out.println(r);
Num = q;
}
}
}

20) Write a program to find sum of digit of number entered


by user. (winter 16, summer 17) 4 marks
class Sumdigit
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]); //takes argument
as commandline
int remainder, result=0;
while(num>0)
{
remainder = num%10;
result = result + remainder;
num = num/10;
}
System.out.println("Sum of digit of number is : "+result);
}
}
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

21) Write a program to find the number of and sum of all


integers greater than 100 and less than 200 that are divisible
by 7. (Winter 16) 4 marks
class SumInt
{
public static void main(String args[])
{
double sum=0;
int numcnt=0;
for(int i=101;i<200;i++)
{
if(i%7==0)
{
sum=sum+i;
numcnt++;
}
}
System.out.println(" No of elements : "+numcnt);
System.out.println(" Sum of elements : "+sum);
}
}

22) Write a program to generate Fibonacci series 1 1 2 3 5 8


13 21 34 55 89
import java.io.*;
class fibonacci {
static int fib(int n)
{
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}

public static void main(String args[])


{
int n = 9;
System.out.println(fib(n));
}
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

23) Write a program to check whether an entered number is


prime or not? (Winter 15, 17 and summer 16) 4 marks
import java.io.*;
class PrimeNo
{
public static void main(String args[]) throws IOException
{
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter number: ");
int num=Integer.parseInt(bin.readLine());
int flag=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
System.out.println(num + " is not a prime number");
flag=1;
break;
}
}
if(flag==0)
System.out.println(num + " is a prime number");
}
}

24) Write a program to print the following output.


11111
2222
333
44
5
(Winter 17) 4 marks
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

class Sample
{
public static void main(String args[]){
inti,j,a=1;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.println(a+" ");
}
System.out.println(“\n”);
a++;
}
}

25) Write a java program to display all the odd numbers


between 1 to 30 using for loop and if statement
(Summer 18) 8 marks
class OddNum
{
public static void main(String args[])
{
for(int i=1;i<=30;i++)
{
if(i%2 ==1)
{
System.out.print("Odd number :"+i +"\n");
}
}
}
}
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

26) Write a java program to display


*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
public class Series_12
{
public static void main(String[] args)
{
for(i=1; i =<5 ;++i){
System. out.println();
for(j=1;j<=i ;++j)
System. out.print("a");
}
}

27) Write a java program to display


1
12
123
1234
12345
public class Series_12
{
public static void main(String[] args)
{
int size=5;

for(int i=1;i<=size;i++)
{
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

for(int j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println("");
}
}
}

28) Write general syntax of any two decision making


statements and give example. (Summer 16) 4 marks
Decision Making with if statement: The if statement is powerful
decision-making statement & is used to control flow of execution of
statements. The if statement is the simplest one in decision
statement. The if keyword is followed by test expression in
parentheses.
a) It is basically a two way decision statement & is used in
conjunction with an expression. It has following syntax: if(test
expression)
b) It allows computer to evaluate expression first & then
depending on value of expression (relation or condition) is
„true‟ or „false‟, it transfers control to a particular statement.
The program has two parts to follow one for “if condition is
true” & the other for “if condition is false”

c) The if statement can be implemented in different forms listed


below
I. Simple if statement: General form of an statement is
if (test condition)
{
statement block;
}
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

statement n;
Statement in block may be single statement or multiple
statement. If condition is true then statement block will
be executed otherwise block is skipped & statement n
is executed

II. The if……else statement: General form is


if (test condition)
{
True-statement block;
}
else
{
False-statement block;
}
If test expression is true, then true block statement (s)
following the if statement are executed otherwise,
false-block statement(s) are executed. In both cases
statement “n” will always executed.

Program to demonstrate if……else & find maximum


of two numbers.
class maxof
{
public static void main(String args[])
{
int i=78;
int j=67;
if(i>j)
System.out.println (i+” is greater than “+j);
else
System.out.println(j+” is greater than “+i);
}
}

III. Nested if ….. else Statement: When series of decision


are involved , more than one if else statements are
used in nested. General form is
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

if (test condition 1)
{
if (test condition2)
{
statement block 1;
}
else
{
statement block 2;
}
else
{
statement block 3;
}
statement n;
If condition-1 is false, statement block-3 will be
executed; otherwise it continues to perform second
test. If condition-2 true, the statement block-1 will be
evaluated; otherwise statement block-2 will be
evaluated & then control is transferred to statement n.
In nesting care should be taken for every if with else.

IV. The else ……if ladder: When multipath decision are


involved either nested if or else ……if ladder can be
used. A multipath decision is chain of it’s in which
statement associated with each else is an if. General
form is:
if (condition 1)
statement 1;
else if (test condition2)
statement 2;
else if (test condition3)
statement 3;
.
.
else if (test conditionn)
statement n;
else
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

default statement;
statement x;
This construction is known as else……if ladder. The conditions are
evaluated from top (of the ladder) to downwards. As soon as true
conditions are found, statement associated with it is executed &
control is transferred to statement-n (skipping the rest of the
ladder). When all the n conditions becomes false, then final else
containing default statement will be executed.
Switch Statement:
a) Java has built-in multi way decision statement known as
switch. it can be used instead of if or nested if…..else.
b) General form:
switch(expression)
{
case value 1:
block 1;
break;
case value 2:
block 2;
break;
.
.
.
default:
default block;
break;
}
statement n;
c) The expression is an integer expression or character. value1,
value2…. Value n are constants or constant expressions
which must be evaluated to integral constants are known as
case labels. Each of these values should be unique within
switch statement. Block1, block 2 are statement lists & may
contain zero or more statements. There is no need to put
braces around these blocks but case labels must end with
colon ( : ).
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

d) When switch is executed, value of expression is successively


compared against values value 1, value-2. If case is found
whose value matches with value of expression, then block
statements that follows case are executed.
e) The break statement at end of each block signals end of
particular case & causes exit from switch statement &
transferring control to statement following switch.
f) The default is optional case. When present it will be
executed if value of expression does not match with any of
cases values. If not present, no action takes place when all
matches fail & control goes to statement –x.
The?: Operator
a) Java language has an ternary operator, useful for making
two-way decisions. This operator is combination of ? &:,
Takes three operand so it is called as ternary operator. This
operator is popularly known as conditional operator. General
form of use of conditional operator is:
conditional expression? expression 1 : expression 2
b) The conditional expression is evaluated first. If result is true,
expression 1 is evaluated & is returned as value of
conditional expression. Otherwise, expression 2 is evaluated
& its value is returned. For example,
if (a<0)
flag = 0;
else
flag = 1;
can written as flag = (a<0) ? 0 : 1
c) When conditional operators is used, code becomes more
concise & perhaps , more efficient. However readability is
poor. It is better to use if statements when more than single
nesting of conditional operator is required.
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

29) Explain break and continue statements with example


(Summer 16) 4 marks
a) Break:
The break keyword is used to stop the entire loop. The break
keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost
loop and start executing the next line of code after the block
Example:
public class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}

b) Continue:
The continue statement skips the current iteration of a for,
while , or do-while loop. The unlabeled form skips to the end
of the innermost loop's body and evaluates the boolean
expression that controls the loop.
A labeled continue statement skips the current iteration of an
outer loop marked with the given label.
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

System.out.print( x );
System.out.print("\n");
}
}
}

30) State syntax and describe working of “for each” version


of for loop with one example. (Summer 16) 4 marks

The For-Each Alternative to Iterators


If you won‟t be modifying the contents of a collection or obtaining
elements in reverse order, then the for-each version of the for loop
is often a more convenient alternative to cycling through a
collection than is using an iterator. Recall that the for can cycle
through any collection of objects that implement the Iterable
interface. Because all of the collection classes implement this
interface, they can all be operated upon by the for.
// Use the for-each for loop to cycle through a collection.
// Use a for-each style for loop.

Syntax:
for(data_type variable : array | collection)
{}

Example:
ClassForEach
{
public static void main(String args[])
{
intnums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0; // use for-each style for to display and sum the values
for(int x : nums)
{
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

31) Explain with example, use of switch case


(winter 17) 4 marks

Switch case statement:


a) The switch statement is used to select among multiple
alternative
b) It uses all primitive datatypes except boolean expression to
determine which alternative should be executed.
General form:
switch(expression)
{
case value1:
block 1;
break;
case value2:
block 2;
break;
.
.
.
default:
default block;
break;
}
statement n;

Example:
public class SwitchExample {
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

public static void main(String[] args) {


int number=20;
switch(number){
case 10: System.out.println("You are in 10");break;
case 20: System.out.println("You are in 20");break;
case 30: System.out.println("You are in 30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}

32) Describe break and continue statement with example


(Winter 15) 4 marks
a) Break:
The break keyword is used to stop the entire loop. The break
keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost
loop and start executing the next line of code after the block.
Example:
public class TestBreak
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
break;
}
System.out.println( “value of x-“+x );
}
}
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

b) continue:
The continue statement skips the current iteration of a for,
while , or do-while loop. The unlabeled form skips to the end
of the innermost loop's body and evaluates the boolean
expression that controls the loop. A labeled continue
statement skips the current iteration of an outer loop marked
with the given label.
Example:
public class TestContinue
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

33) Define a class and object. write syntax to create class


and object with example. (Summer 18) 4 marks
Java is complete object oriented programming language. All
program code and data reside in object and class. Java classes
create objects and objects will communicate between using
methods

Class: A “class” is a user defined data type. Data and methods are
encapsulated in class. It is a template or a pattern which is used to
define its properties. Java is fully object oriented language. All
program code and data reside within objects and classes.
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

Syntax :

Object: It is a basic unit of Object Oriented Programming and


represents the real life entities. A typical Java program creates
many objects, which as you know, interact by invoking methods.
An object consists of state ,behavior and identity
Syntax:
class_name object=new class_name()

Example:
class Student{
int id; //field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student(); //creating an object of Student
System.out.println(s1.id); //accessing member through reference
variable
System.out.println(s1.name);
}}

34) What is the use of new operator? Is it necessary to be


used whenever object of the class is created? Why?
(winter 16) 4 marks
Use:
a) new operator is used to dynamically allocate memory to
the object of the class. It is the operator which is used to
create usable instance of the class. It is generally used
BASIC SYNTACTICAL CONSTRUCTS IN JAVA

along with the constructor of the class so as to get


memory allocated to the object.
b) It is necessary to use new operator whenever an object
requires memory allocation after creation. Otherwise
object in the form of reference is created which will point
to Null, i.e. with no allocated space in memory.

You might also like