0% found this document useful (0 votes)
7 views40 pages

Java

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)
7 views40 pages

Java

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/ 40

Basics of Java

1. Overview of Java

 Java is a high-level, object-oriented, platform-independent programming language


developed by Sun Microsystems (now owned by Oracle).

 It follows the principle of “Write Once, Run Anywhere (WORA)” because compiled Java
programs can run on any machine with a JVM.

2. History and Evolution of Java

 1991: Project "Green" started by James Gosling and team at Sun Microsystems.

 1995: Java officially released.

 Initially called Oak, later renamed Java (inspired by Java coffee).

 Designed for embedded systems but became popular for web, desktop, and enterprise
applications.

Key Features of Java

 Platform Independent: Java is famous for its Write Once, Run Anywhere (WORA)
feature. This means we can write our Java code once, and it will run on any device or
operating system if Java Virtual Machine is installed.

 Simple: No complex features like pointers and multiple inheritance, which makes it a
good choice for beginners.

 Object-Oriented: This makes code clean and reusable.

 Secured: Since there are no pointers, it has built-in protections to keep our programs
secure from memory leakage and segment fault.

 Multithreading: Programs can do many things at the same time using multiple threads.
This is useful for handling complex tasks like processing transactions.

 Just-In-Time (JIT) Compiler: JIT is part of JVM.

 It translates Java bytecode into machine code at runtime (just before execution).
 This makes execution faster.
 Helps Java run with high performance.

 Robust – Automatic garbage collection, exception handling.


 Portable – Java bytecode can run anywhere.
How does this work:

 class → blueprint of program

 main() → entry point of program

 System.out.println() → prints output

 // starts a single-line comment. The comments do not get executed by Java.

 public class HelloWorld defines a class named HelloWorld. In Java, every program must
be inside a class.

 public static void main(String[] args) is the entry point of any Java application. It tells
the JVM where to start executing the program.

 System.out.println("Hello, World!"); prints the message to the console.


 Write code in a file like HelloWorld.java.

 The Java Compiler "javac" compiles it into bytecode "HelloWorld.class".

 The JVM (Java Virtual Machine) reads the .class file and interprets the bytecode.

 JVM converts bytecode to machine readable code i.e. "binary" (001001010) and then
execute the program.

Difference between Java, C++ and C

Feature C C++ Java

Paradigm(approach or method used to design Procedural +


Procedural Pure OOP (except primitives)
and write programs) OOP

Platform Platform
Platform Platform independent (JVM)
dependent dependent

C (Manual – C++ (Manual – Automatic (When an object is no


Memory management longer used, Garbage Collector (GC)
malloc, free) new, delete)
removes it.)

Multiple inheritance Not supported Supported Not supported (uses interfaces)

Compilation/Execution Compiler only Compiler only Compiler + JVM interpreter

JDK, JRE and JVM

 JDK (Java Development Kit): Tools to develop Java applications (compiler +


libraries + JRE).

 JRE (Java Runtime Environment): Contains JVM + libraries to run Java programs.

 JVM (Java Virtual Machine): Converts bytecode into machine code and runs the
program.

Here’s the JDK, JRE, JVM difference in table form (easy for viva):
JVM (Java
JRE (Java Runtime JDK (Java
Feature Virtual
Environment) Development Kit)
Machine)

Java Virtual Java Runtime Java Development


Full Form
Machine Environment Kit

Package that Package that


A program that
What it provides JVM + provides JRE + tools
runs Java
is libraries to run Java to develop Java
bytecode
programs programs

Used to develop +
Executes Java Used to run Java
Use run Java
bytecode applications
applications

Interpreter +
JRE + compiler
JIT compiler +
Contains JVM + core libraries (javac), debugger,
Garbage
other tools
Collector

For programmers
For For executing For users who want
who want to create
whom code to run programs
programs

👉 In short:

 JVM → Runs Java code

 JRE → Runs Java programs

 JDK → Develops + Runs Java programs

Structure of a Java Program:


java Hello is calling class of the program

Java Data Types

In Java, data types specify the kind of values a variable can store.
They are divided into Primitive and Non-Primitive (Reference) types.
1. Primitive Data Types (built-in, 8 types)

These are the basic types, directly supported by the Java language.

🔹 Boolean Type

 boolean → stores only true/false values.

 Size: 1 bit (depends on JVM).

 Example: boolean isJavaFun = true;

🔹 Numeric Types

Divided into Integral and Floating Point types.

Integral Types (whole numbers)

 byte → 8-bit, range: -128 to 127

 short → 16-bit, range: -32,768 to 32,767

 int → 32-bit, range: -2^31 to 2^31-1

 long → 64-bit, range: -2^63 to 2^63-1

Character Type

 char → 16-bit Unicode character.

 Stores a single character (e.g., 'A', '9').

Floating Point Types (decimal values)

 float → 32-bit, single precision, ~7 decimal digits.

 double → 64-bit, double precision, ~15 decimal digits.

2. Non-Primitive (Reference) Data Types

These are objects created from classes. They can store more complex data.

 String → sequence of characters (e.g., "Hello World").

 Array → collection of elements of same type (e.g., int[] arr = {1,2,3};).

 Class & Objects → user-defined types (blueprint and its instance).


 Interfaces, Enums → also reference types.

Hierarchy (Easy to Remember)

 Primitive

o Boolean → boolean

o Numeric

 Integral → byte, short, int, long, char

 Floating Point → float, double

 Non-Primitive

o String

o Array

o Objects

👉 In short:

 Primitive = 8 fixed basic types (boolean, byte, short, int, long, char, float, double).

 Non-Primitive = created by user or Java (String, Array, Objects, etc.).

Elements of Java

1. Keywords

 Reserved words, cannot be used as identifiers.

 Examples: class, int, static, public, void, if, else.

2. Data Types

 Primitive: byte, short, int, long, float, double, char, boolean.

 Non-Primitive: String, Arrays, Classes, Interfaces.


3. Variables

 Storage for data.

 Declaration: int a;

 Initialization: a = 10;

 Combined: int a = 10;

Scope & Lifetime:

 Local Variable: Inside methods, exist during method execution.

 Instance Variable: Inside class but outside methods, exist with object.

 Static Variable: Shared among all objects, exists till program ends.

4. Constants

 Declared using final keyword.

 Example: final double PI = 3.14;

5. Literals

 Fixed values used directly in code.

 Example: 10, 3.14, 'A', "Hello".

6. Identifiers

 Names for variables, methods, classes.

 Rules: Must start with letter, $, or _, cannot use keywords.

7. Operators

 Arithmetic: + - * / %

 Relational: == != > < >= <=

 Logical: && || !

 Assignment: = += -=

 Unary: ++ --
 Bitwise: & | ^ ~ << >>

 Ternary: condition ? true : false

8. Types of Java Statements

 Declaration Statements → int a = 10;

 Expression Statements → a = a+1;

 Control Statements → if, switch, for, while, do-while, break, continue, return.

9. Unicode System

 Java uses Unicode (16-bit) → Supports all international characters.

 Example: char c = '\u0041'; // A

10. Naming Convention

 Class → PascalCase (e.g., StudentDetails)

 Method/Variable → camelCase (e.g., getName())

 Constants → UPPER_CASE (e.g., MAX_VALUE)

 Package → lowercase (e.g., java.util)

11. Comments

 Single-line: // comment

 Multi-line: /* comment */

 Documentation: /** comment */

12. Arrays

 Collection of same type elements.

int arr[] = {1, 2, 3};


13. Type Conversion and Casting

 Implicit (Widening): Smaller → Bigger type (automatic).


Example: int a = 10; double d = a;

 Explicit (Narrowing): Bigger → Smaller (requires casting).


Example: double d = 10.5; int a = (int) d;

Nice 👍 you want a complete exam-preparation style summary of Java basics (with C
comparison). I’ll prepare this like notes/cheat-sheet so you can revise quickly before
exams/viva.

Java Exam Preparation Notes

1. Difference between Java and C

Feature C Java

Paradigm Procedural Object-Oriented (mostly)

Platform dependent (compiled to Platform independent (compiled to


Platform
machine code) bytecode, runs on JVM)

Memory
Manual (malloc/free) Automatic (Garbage Collector)
Management

Pointers Supported Not supported (for safety)

Inheritance Not supported Supported via classes & interfaces

Compilation Compiler only Compiler + JVM (JIT + Interpreter)

2. Control Statements

🔹 Jump Statements

 break → exits loop/switch.

 continue → skips current iteration, moves to next.

 return → exits method and optionally returns a value.

 goto → not in Java (unsafe).


🔹 Conditional Statements

 if

 if-else

 if-else-if ladder

 switch-case

🔹 Loop Statements

 for → loop with initialization, condition, update.

 foreach (enhanced for) → iterates over arrays/collections.

 while → checks condition first, then executes.

 do-while → executes at least once, then checks condition.

Difference between Loops:

 for → known number of iterations.

 while → condition-based, may not execute.

 do-while → executes at least once.

 foreach → easy array/collection traversal.

3. Java Operators (7 Types)

1. Arithmetic → + - * / %

2. Relational → > < >= <= == !=

3. Logical → && || !

4. Bitwise → & | ^ ~ << >> >>>

5. Assignment → =, +=, -=, *= etc.

6. Unary → ++ -- + - !

7. Ternary → condition ? true : false

4. Keywords
 Reserved words (like class, if, while) that cannot be used as identifiers.

 67 in Java (e.g., int, static, final, new, return).

5. Data Types

 Primitive (8 types): boolean, byte, short, int, long, char, float, double.

 Non-Primitive: String, Arrays, Classes, Objects, Interfaces.

6. Variables, Scope & Lifetime

 Local variable → inside method/block, exists until method finishes.

 Instance variable → inside class but outside methods, tied to objects.

 Static variable → shared by all objects, exists till program ends.

7. Constants

 Declared using final.

 Example: final double PI = 3.14;

8. Literals

Integral Literals:

 Decimal: int x = 10;

 Octal: int y = 012; (starts with 0)

 Hexadecimal: int z = 0xA;

 Binary: int b = 0b1010;

Character Literals:

 'A' (single quote)

 'A' = 65 (integral value in Unicode)

 Unicode: '\u0041' = 'A'


 Escape sequences: '\n', '\t', '\''

String Literal: "Hello Java"

Boolean Literal: true, false

9. Identifiers

 Names for variables, methods, classes.

 Rules: cannot be keyword, no spaces, start with letter/_, case-sensitive.

10. Types of Java Statements

 Expression statement → a = b + c;

 Declaration statement → int x = 5;

 Control flow statements → if, for, while.

11. Unicode System

 Java uses Unicode (16-bit) → supports international characters.

12. Naming Conventions

 Class → PascalCase (StudentData)

 Variable/Method → camelCase (studentName, getData())

 Constants → UPPERCASE (MAX_VALUE)

 Package → lowercase (java.util)

13. Comments

 Single line → //

 Multi-line → /* ... */

 Documentation → /** ... */


14. Arrays

 Features: fixed-size, same data type, indexed (0-based).

 Declaration: int[] arr;

 Initialization: int[] arr = {1,2,3};

 Accessing/Updating: arr[0] = 10;

 Advantages: Easy to access, memory efficiency.

 Disadvantages: Fixed size, cannot grow dynamically (use ArrayList).

15. Type Conversion & Casting

 Widening (Implicit) → smaller to bigger (int → long).

 Narrowing (Explicit) → bigger to smaller (double → int).

 int x = (int) 3.5; // Casting

16. Blocks

 Method block → code inside a method.

 Class block → code inside a class definition.

17. Class

 Modifiers: public, abstract, final.

 Structure:

 class Student extends Person implements Serializable {

 int id;

 String name;

 }

 Superclass → Inherited parent class.


 Interfaces → For multiple inheritance.

 Body → Contains fields, methods, constructors.

✅ This covers everything you listed in easy-to-read exam prep format.

Would you like me to make a mindmap-style diagram (one-page summary) so you can revise all
these topics quickly?

Perfect 👍 Let’s go through these topics one by one in easy exam-prep style with examples so
you’ll understand and also have short notes for viva.

2. Control Statements in Java

Control statements decide flow of execution in a program.

🔹 (a) Conditional Statements

public class IfElseExample {

public static void main(String[] args) {

int age = 18;

if (age >= 18) {

System.out.println("You can vote!");

} else {

System.out.println("You cannot vote!");

 if → checks a condition.

 if-else → runs one block if true, another if false.

 if-else-if ladder → multiple conditions.

 switch-case → many choices.

int day = 2;
switch(day) {

case 1: System.out.println("Monday"); break;

case 2: System.out.println("Tuesday"); break;

default: System.out.println("Other day");

🔹 (b) Looping Statements

for loop

for(int i=1; i<=5; i++) {

System.out.println(i);

while loop

int i=1;

while(i<=5) {

System.out.println(i);

i++;

do-while loop

int j=1;

do {

System.out.println(j);

j++;

} while(j<=5);

foreach loop

int[] arr = {10, 20, 30};

for(int num : arr) {


System.out.println(num);

🔹 (c) Jump Statements

 break → exits loop/switch.

 continue → skips current iteration.

 return → exits method.

for(int i=1; i<=5; i++) {

if(i==3) continue; // skips 3

System.out.println(i);

3. Java Operators (7 Types)

1. Arithmetic → + - * / %

2. int a=10, b=3;

3. System.out.println(a+b); // 13

4. System.out.println(a%b); // 1

5. Relational → > < >= <= == !=

6. System.out.println(a>b); // true

7. Logical → && || !

8. System.out.println(a>5 && b<5); // true

9. Bitwise → & | ^ ~ << >>

10. System.out.println(5 & 3); // 1

11. Assignment → = += -= *= /=

12. int x=5;

13. x+=2; // x=7


14. Unary → ++ -- + - !

15. int y=5;

16. System.out.println(++y); // 6

17. Ternary → ? :

18. int max = (a>b) ? a : b;

4. Instance Variable vs Static Variable

 Instance Variable

o Declared inside class but outside methods.

o Each object has its own copy.

 class Student {

 String name; // instance variable

 }

 Static Variable

o Declared with static.

o Shared by all objects of the class.

 class Student {

 static String school = "ABC School"; // same for all

 }

5. Constants

 Declared using final keyword → value cannot change.

 Often also declared static → so one copy is shared by all objects.

class Circle {

static final double PI = 3.14159;

}
👉 Why final + static?

 final → makes value unchangeable.

 static → avoids creating multiple copies for each object.

6. Literals in Java

Literals = fixed values written directly in code.

 Integral Literals → int x=10; (decimal), int y=012; (octal), int z=0xA; (hex), int b=0b1010;
(binary).

 Character Literal → 'A', '\n', '\u0041'.

 String Literal → "Hello".

 Boolean Literal → true, false.

7. Modifiers

 public → accessible everywhere.

 abstract → class or method without full implementation (must be subclassed).

 final → cannot be inherited (for class), cannot be overridden (for method), cannot be
changed (for variable).

8. Class Body

A class body contains:

 Fields (variables)

 Methods

 Constructors

Example:

public class Student {

// Field

String name;
// Constructor

Student(String n) {

name = n;

// Method

void display() {

System.out.println("Name: " + name);

✅ This covers all the points you asked with definitions + examples.

Would you like me to also make a one-page table (quick revision sheet) for all these topics?

Got it 👍 Let me explain these clearly and simply so it sticks for exams/viva.

1. Static Variable

 Declared with the keyword static inside a class.

 Shared by all objects of the class (only one copy exists).

 Memory is allocated once (when class loads), not for every object.

👉 Example:

class Student {

String name; // instance variable

static String school = "ABC School"; // static variable

Student(String n) {
name = n;

public class Test {

public static void main(String[] args) {

Student s1 = new Student("Ravi");

Student s2 = new Student("Maya");

System.out.println(s1.name + " studies in " + Student.school);

System.out.println(s2.name + " studies in " + Student.school);

✅ Here, school is the same for all students. If changed once, it changes for everyone.

2. Modifiers (Definition)

In Java, modifiers are keywords that change the meaning or behavior of classes, methods, or
variables.
They are of two types:

🔹 Access Modifiers (control visibility)

 public → accessible everywhere.

 protected → accessible within package + subclasses.

 default (no keyword) → accessible within same package only.

 private → accessible only inside the same class.

🔹 Non-Access Modifiers (provide extra features)

 static → variable/method belongs to class (not object).

 final → cannot be changed (constant for variable, can’t be overridden for method, can’t
be inherited for class).

 abstract → used for incomplete classes/methods (must be implemented in subclass).


 synchronized, volatile, transient → used in special cases (advanced).

3. Abstract (Clear Explanation)

Abstract = Incomplete, must be completed by child class.

 Declared with abstract keyword.

 Abstract class → a class that cannot be instantiated (cannot create objects directly).

 Abstract method → a method declared without a body (no { }), only signature.

 Subclasses must override the abstract methods.

👉 Example:

abstract class Animal {

abstract void sound(); // abstract method (no body)

class Dog extends Animal {

void sound() {

System.out.println("Bark");

public class Test {

public static void main(String[] args) {

Animal a = new Dog(); // Reference to abstract class, object of Dog

a.sound(); // Output: Bark

✅ Why abstract?
 Provides a blueprint for subclasses.

 Ensures child classes implement necessary methods.

👉 Quick Summary for Viva

 Static variable → one copy, shared by all objects.

 Modifiers → keywords that control visibility (public/private) or features


(static/final/abstract).

 Abstract → incomplete (class/method), must be extended and implemented by child


classes.

Would you like me to also show a comparison table: static vs instance variable vs final constant
(easy memory aid for exam)?

Perfect 👍 You’ve got a Java lab experiment list (from basics → OOP → advanced concepts).
I’ll give you:

 ✅ Full Java code for each program

 ✅ Explanation of important terms (like inheritance, interface, threads, etc.) in simple


words

🔹 Java Programs with Explanations

1. Accept two numbers and print their sum

import java.util.Scanner;

public class SumTwoNumbers {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.print("Enter first number: ");

int a = sc.nextInt();

System.out.print("Enter second number: ");

int b = sc.nextInt();

int sum = a + b;

System.out.println("Sum = " + sum);

👉 Term: Scanner is a class used to take input from the user.

2. Addition using method prototyping

public class AdditionMethod {

// Method prototype (signature)

static int add(int x, int y) {

return x + y;

public static void main(String[] args) {

int result = add(5, 7);

System.out.println("Sum = " + result);

}
👉 Term: Method prototyping means defining method name, return type, and parameters
before using it.

3. Function overloading for average

public class AverageOverload {

// Overloaded methods

static double average(int a, int b) {

return (a + b) / 2.0;

static double average(int a, int b, int c) {

return (a + b + c) / 3.0;

public static void main(String[] args) {

System.out.println("Average of 2 numbers: " + average(10, 20));

System.out.println("Average of 3 numbers: " + average(10, 20, 30));

👉 Term: Method overloading allows multiple methods with the same name but different
parameter lists.

4. Overloaded constructor for Box volume

class Box {

double length, width, height;

// Default constructor
Box() {

length = width = height = 1;

// Parameterized constructor

Box(double l, double w, double h) {

length = l;

width = w;

height = h;

double volume() {

return length * width * height;

public class BoxVolume {

public static void main(String[] args) {

Box b1 = new Box(); // default

Box b2 = new Box(3, 4, 5); // parameterized

System.out.println("Volume of Box1 = " + b1.volume());

System.out.println("Volume of Box2 = " + b2.volume());

}
👉 Term: Constructor overloading means creating multiple constructors with different parameter
lists.

Program Explanation

🔹 Class Definition

class Box {

double length, width, height;

 A class is a blueprint.

 Box has three instance variables: length, width, height (all of type double).

🔹 Default Constructor

Box() {

length = width = height = 1;

 A constructor is called when an object is created.

 Default constructor sets all dimensions to 1.

 So if you don’t give values, the box will be 1 × 1 × 1.

🔹 Parameterized Constructor

Box(double l, double w, double h) {

length = l;

width = w;

height = h;

 Allows you to initialize the object with given values.

 Example: Box(3, 4, 5) creates a box of those dimensions.


🔹 Method

double volume() {

return length * width * height;

 Method to calculate volume.

 Formula: length × width × height.

Main Class

public class BoxVolume {

public static void main(String[] args) {

Box b1 = new Box(); // Calls default constructor

Box b2 = new Box(3, 4, 5); // Calls parameterized constructor

System.out.println("Volume of Box1 = " + b1.volume());

System.out.println("Volume of Box2 = " + b2.volume());

🔹 Step-by-step:

1. Box b1 = new Box();

o Creates a box with dimensions 1,1,1.

o Volume = 1 × 1 × 1 = 1.

2. Box b2 = new Box(3,4,5);

o Creates a box with dimensions 3,4,5.

o Volume = 3 × 4 × 5 = 60.

3. Output:

Volume of Box1 = 1.0


Volume of Box2 = 60.0

Key Points to Remember for Exams

 Constructors initialize objects (no return type, same name as class).

 Default constructor gives fixed/default values.

 Parameterized constructor allows custom values.

 Methods perform operations on data (here: volume()).

 Objects (b1, b2) are created using new.

5. Inheritance (Student details)

class Person {

String name;

int age;

class Student extends Person {

String course;

void display() {

System.out.println("Name: " + name + ", Age: " + age + ", Course: " + course);

public class InheritanceDemo {

public static void main(String[] args) {


Student s = new Student();

s.name = "Mishika";

s.age = 20;

s.course = "AI Engineering";

s.display();

👉 Term: Inheritance lets a class (child) use fields/methods of another class (parent).

6. Package concept

// File: mypack/HelloPackage.java

package mypack;

public class HelloPackage {

public void display() {

System.out.println("Hello from Package!");

// File: TestPackage.java

import mypack.HelloPackage;

public class TestPackage {

public static void main(String[] args) {

HelloPackage hp = new HelloPackage();

hp.display();
}

👉 Term: A package is a collection of classes, used for better organization.

7. Interface (square & cube)

interface MathOperation {

int square(int x);

int cube(int x);

class OperationImpl implements MathOperation {

public int square(int x) {

return x * x;

public int cube(int x) {

return x * x * x;

public class InterfaceDemo {

public static void main(String[] args) {

OperationImpl op = new OperationImpl();

System.out.println("Square of 4 = " + op.square(4));

System.out.println("Cube of 4 = " + op.cube(4));

}
}

👉 Term: Interface is like a contract: classes must implement all its methods.

8. Exception handling (division by zero)

public class ExceptionDemo {

public static void main(String[] args) {

try {

int a = 10, b = 0;

int c = a / b; // risky

System.out.println("Result = " + c);

} catch (ArithmeticException e) {

System.out.println("Error: Division by zero!");

👉 Term: Exception handling prevents program crash using try-catch.

9. Multithreading

class MyThread extends Thread {

public void run() {

for (int i = 1; i <= 5; i++) {

System.out.println(Thread.currentThread().getName() + " - " + i);

}
public class ThreadDemo {

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

t1.start();

t2.start();

👉 Term: Multithreading allows multiple parts of a program to run at the same time.

10. Hello World Applet

import java.applet.Applet;

import java.awt.Graphics;

/* <applet code="HelloApplet" width=300 height=100></applet> */

public class HelloApplet extends Applet {

public void paint(Graphics g) {

g.drawString("Hello World", 100, 50);

👉 Term: Applet is a Java program that runs in a browser (old technology).

11. Applet with User Controls

import java.applet.*;

import java.awt.*;
import java.awt.event.*;

/* <applet code="ButtonApplet" width=300 height=100></applet> */

public class ButtonApplet extends Applet implements ActionListener {

Button b;

String msg = "";

public void init() {

b = new Button("Click Me");

add(b);

b.addActionListener(this);

public void actionPerformed(ActionEvent e) {

msg = "Button Clicked!";

repaint();

public void paint(Graphics g) {

g.drawString(msg, 100, 80);

12. Swing Application

import javax.swing.*;
public class SwingDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("Swing Example");

JButton button = new JButton("Click Me");

button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Hello Swing!"));

frame.add(button);

frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

👉 Term: Swing is a Java library to build GUI applications.

⚡ So, difficulty increases step by step:

 Programs 1–4 → Basic Java

 Programs 5–8 → OOP Concepts

 Programs 9–12 → Advanced (Multithreading, GUI, Applets, Swing)

In Java, the symbols +, -, *, /, and % are known as arithmetic operators. +: Addition operator, -:
Subtraction operator, *: Multiplication operator, /: Division operator, and %: Modulo operator
(returns the remainder of a division).

Integer Division (when both operands are integers):

When you divide two integers, Java performs integer division, which means any fractional part
of the result is truncated (discarded). The result will also be an integer.
Java

public class DivisionExample {


public static void main(String[] args) {
int a = 10;
int b = 3;
int result = a / b; // Integer division
System.out.println("10 / 3 (integer division) = " + result); // Output: 3
}
}

2. Floating-Point Division (when at least one operand is a floating-point type


like double or float):

If at least one of the operands is a floating-point type, Java performs floating-point division, and
the result will be a floating-point number, including the decimal part.

Java

public class DivisionExample {


public static void main(String[] args) {
double c = 10.0; // Using a double literal
int d = 3;
double result1 = c / d; // Floating-point division
System.out.println("10.0 / 3 (floating-point division) = " + result1); // Output:
3.3333333333333335

double e = 10; // Implicitly converts 10 to 10.0


double f = 3;
double result2 = e / f; // Floating-point division
System.out.println("10 / 3 (both double) = " + result2); // Output: 3.3333333333333335
}
}
Got it 👍 I’ll prepare a simple Java code (small but covering important concepts for viva) + give
you explanation of each part so you can easily answer oral questions.

✅ Java Code (covers basics: class, object, constructor, methods, static, final, etc.)

// A simple Java program for Viva

class Student {

// Data members (variables)

String name;

int rollNo;

static String college = "ABC College"; // static variable (common for all)

// Constructor (used for initialization)

Student(String n, int r) {

name = n;

rollNo = r;

// Method (behavior of object)

void display() {

System.out.println("Name: " + name + ", Roll No: " + rollNo + ", College: " + college);

// Final method (cannot be overridden)

final void showCollege() {

System.out.println("College is: " + college);

}
}

public class VivaExample {

public static void main(String[] args) {

// Creating objects (using constructor)

Student s1 = new Student("Mishika", 101);

Student s2 = new Student("Arjun", 102);

// Calling methods

s1.display();

s2.display();

// Accessing final method

s1.showCollege();

🔑 Explanation of Important Things (for viva)

1. Class

 Blueprint of an object.

 Here: class Student is the blueprint.

2. Object

 Instance of a class created using new.

 Example: Student s1 = new Student("Mishika", 101);

3. Constructor

 Special method used to initialize objects.


 Same name as class, no return type.

 Example: Student(String n, int r)

4. Methods

 Define behavior of objects.

 Example: display() prints student details.

5. Static keyword

 Belongs to the class, not object.

 Same for all objects.

 Example: static String college = "ABC College";

6. Final keyword

 If applied to variable → value cannot be changed (constant).

 If applied to method → cannot be overridden.

 Example: final void showCollege()

7. Main method

 Entry point of the program.

 Syntax: public static void main(String[] args)

8. System.out.println()

 Used to print output on the console.

✅ Sample Output

Name: Mishika, Roll No: 101, College: ABC College

Name: Arjun, Roll No: 102, College: ABC College

College is: ABC College

👉 This single program is enough to discuss:

 Class & Object


 Constructor

 Methods

 Static & Final

 Main method

 Output explanation

Do you want me to also prepare a very short set of viva-style Q&A (like “What is constructor?”,
“Why static keyword?”) based on this code so you can practice quick answers?

You might also like