TUpapers logo TUpapers.com

Explore TUpapers

Study materials and tools in one place.

  • Dashboard
  • Blog
  • Search
  • About

Follow us

TUpapers on Facebook
TUpapers on Instagram
Contact TUpapers on WhatsApp
TUpapers subreddit on Reddit
Student Dashboard Student Dashboard
TUpapers logo TUpapers.com
  • Blog
  • About

Support Us

Your support helps us for further development and maintenance of site and resources!

Bank QR code for payment
eSewa QR code for payment
Khalti QR code for payment

The best way to support TUpapers is by purchasing a Premium Suscription or Notes Every purchase directly funds new features, better study resources, and platform maintenance.

On this chapter

Introduction to Java

All Chapters

Dashboard

Select a chapter to start reading

Object Oriented Programming with Java Notes | BITM Second Semester | TU Papers

1 Chapter 1 Preview

No preview available.

Notes for this subject are coming soon — check back later.

Student Dashboard

Continue Reading

Get full notes inside the dashboard, along with other study tools.

Unit 1: Introduction to Java [5 Hours]

Java is a general-purpose, class-based programming language designed to make software portable, secure, reliable, and suitable for many kinds of applications. This unit covers Java's origin, its relationship with earlier programming languages, its role in Internet-based software, major Java features, the Java execution environment, bytecode and platform independence, basic program development, Object-Oriented Programming (OOP), command-line arguments, keyboard input, and console output.

Tested Topics

  1. Scanner class for input — 2x (October 2023, March-April 2023)
  2. Bytecode significance — 1x (March-April 2023)
  3. Java Buzzwords — 1x (October 2023)
  4. Java's impact on the Internet — 1x (Model Q)
  5. JVM, JRE, and JDK architecture — 1x (Model Q)

1.1 The Creation of Java

Definition

Java is a high-level, class-based programming language created at Sun Microsystems to develop reliable software that could run on different types of computer systems.


Java began as a project for programming electronic devices. The developers wanted one program to work on different hardware without rewriting it for every machine. This idea later became one of Java's defining properties: software is compiled into a portable form that a Java runtime can execute on different platforms.

Detailed Explanation

Java was developed by a team at Sun Microsystems led by James Gosling. Work began in the early 1990s as part of a project often associated with intelligent consumer-electronic devices and embedded systems.

The original language was named Oak. It was designed for devices whose processors and operating environments could differ greatly. A language tightly dependent on one processor would have created a major problem because every version of the device could require a separately compiled program.

The design therefore emphasized:

  • Portability: the same compiled program should be usable on different machines.
  • Reliability: common sources of programming errors should be reduced.
  • Security: programs should execute within a controlled runtime environment.
  • Object-oriented design: software should be structured using classes and objects.
  • Automatic memory management: programmers should not have to manually release ordinary dynamically allocated objects.

As the Internet and the World Wide Web expanded during the 1990s, Java's portability became useful beyond embedded devices. The language was renamed Java and publicly introduced by Sun Microsystems in 1995.

Why Java's Creation Was Different

Traditional native programs are normally compiled for a particular processor and operating system. Java introduced an intermediate representation called bytecode. Java source code is compiled into bytecode, and a Java Virtual Machine later executes that bytecode.

The basic idea is:

Java source code → Java compiler → bytecode → Java Virtual Machine → machine execution

This design separates the compiled Java program from the specific hardware on which it eventually runs.

Summary

  • Java was developed at Sun Microsystems under the leadership of James Gosling.
  • The language began as Oak during work on software for different types of electronic systems.
  • Portability, reliability, security, and object-oriented design were major design goals.
  • The language was renamed Java and publicly introduced in 1995.
  • Its bytecode-based execution model helped separate programs from specific hardware architectures.

1.2 Java's Lineage and Its Influence on Modern Programming

Definition

Java's lineage refers to the earlier programming languages and programming ideas that influenced Java's syntax and design.


Java did not appear independently from earlier languages. Its syntax looks familiar to programmers who know C and C++, while its designers changed or removed several difficult features to produce a safer and more portable programming environment.

Detailed Explanation

The clearest language relationship can be understood as:

C → C++ → Java

Influence of C

C strongly influenced Java's basic syntax. Java uses many familiar C-style elements, including:

  • Curly braces { } for blocks.
  • Semicolons to terminate statements.
  • Operators such as +, -, *, /, ==, and &&.
  • Control structures such as if, switch, for, while, and do-while.
  • Primitive data types and expression-oriented syntax.

Influence of C++

C++ extended C with object-oriented features, and Java adopted many of the same broad ideas:

  • Classes and objects.
  • Encapsulation.
  • Inheritance.
  • Polymorphism.
  • Constructors.
  • Method overloading.

Java did not copy every C++ feature. Its designers deliberately changed or omitted features that could make programs difficult to manage or unsafe.

AreaC++Java
Memory managementCan use explicit allocation and deallocationUses automatic garbage collection for ordinary objects
Pointer arithmeticSupportedNot exposed to programmers
Multiple inheritance of classesSupportedNot supported directly; interfaces provide a different mechanism
Operator overloadingBroadly supportedProgrammers cannot define general custom operator overloads
PreprocessorUses directives such as #includeNo C-style preprocessor
ExecutionUsually compiled to native machine codeCompiled to bytecode for execution by the Java Virtual Machine

Influence on Modern Programming

Java helped make several programming practices common in mainstream software development. These include managed execution environments, automatic garbage collection, standard exception handling, extensive standard libraries, portable intermediate code, built-in support for multithreading, and strong runtime type checking.

Java also became widely used in enterprise applications, server software, educational programming, Android's early application ecosystem, development tools, and large networked systems. Languages and platforms developed later often use comparable concepts such as managed runtimes, virtual machines, garbage collection, class libraries, and intermediate representations.

Let's Clarify

A family tree is a useful way to understand Java's lineage. C contributed much of the surface syntax. C++ added a strong object-oriented direction. Java kept many familiar ideas but redesigned the environment around portability, memory safety, and managed execution.

Summary

  • Java's syntax is strongly influenced by C and C++.
  • C contributed familiar operators, statements, expressions, and block syntax.
  • C++ influenced Java's class-based object-oriented design.
  • Java removed or restricted several complex low-level features such as pointer arithmetic.
  • Java helped popularize managed runtimes, garbage collection, portable intermediate code, and rich standard libraries.

Test Yourself

  1. Explain the relationship among C, C++, and Java.
  2. Name four C++-style features retained by Java and two features Java does not directly support.

Hints:

  1. C influenced Java's syntax; C++ contributed class-based object-oriented ideas; Java redesigned them around portability and managed execution.
  2. Classes, objects, inheritance, polymorphism; Java avoids pointer arithmetic and direct multiple inheritance of classes.

1.3 Java's Impact on the Internet

Definition

Java's impact on the Internet came from its ability to provide portable, network-aware, secure programs that could execute through a standardized Java runtime on different systems.


Internet users may use different processors and operating systems. Java's execution model reduced the need to create a completely different program for each type of computer, while its libraries provided built-in support for networking and distributed applications.

Detailed Explanation

The Internet connects heterogeneous systems. A network may include computers running different operating systems and using different processor architectures. Software distributed across such an environment benefits greatly from platform independence.

1. Portability Across Internet-Connected Systems

A Java program can be compiled into bytecode. Any compatible Java Virtual Machine can then execute that bytecode. This made Java well suited to an environment where the developer could not know exactly which computer would receive the software.

2. Historical Role of Java Applets

Early Java became famous partly because of Java applets. An applet was a small Java program designed to be delivered through a web page and executed by a Java-enabled browser or browser plug-in.

Applets historically demonstrated an important idea:

Server sends portable Java bytecode → user's system provides Java runtime → program executes locally

Modern web browsers no longer support traditional Java applets, so applets are now mainly of historical importance when discussing Java's early Internet impact.

3. Security

Downloading executable programs from a network creates security concerns. Java's runtime model included mechanisms intended to control and verify code before and during execution.

Important security-related ideas include:

  • Bytecode verification: the runtime checks bytecode structure before normal execution.
  • No exposed pointer arithmetic: ordinary Java programs cannot directly manipulate arbitrary memory addresses.
  • Class loading controls: classes are loaded through controlled runtime mechanisms.
  • Type checking: many invalid operations are prevented by the language and runtime type system.

4. Networking Support

Java provides standard libraries for network programming. Programs can communicate using network addresses, sockets, web resources, and higher-level networking mechanisms without implementing all low-level networking details manually.

5. Server-Side and Distributed Applications

Java later became especially significant on the server side. Java applications have been used for web servers, application servers, enterprise systems, banking systems, network services, and distributed applications.

Key Aspects of Java's Internet Impact

AspectContribution
PortabilityBytecode can run on different systems that provide a compatible Java Virtual Machine.
SecurityManaged execution reduces direct access to unsafe low-level operations.
NetworkingStandard libraries provide built-in network programming capabilities.
Dynamic loadingClasses can be loaded when required during execution.
MultithreadingPrograms can perform multiple activities concurrently.
Distributed systemsJava supports applications whose components communicate over networks.

Summary

  • Java's portability suited the Internet's mixture of hardware and operating systems.
  • Java applets historically demonstrated downloadable executable content, although applets are now obsolete in modern browsers.
  • Java provides controlled execution and strong type checking for safer network-delivered software.
  • Its standard libraries contain substantial networking support.
  • Java became widely used for server-side and distributed applications.

Test Yourself

  1. How does Java's platform-independent model help Internet applications?
  2. List the Key Aspects of Java's Impact on the Internet. (Model Q)

Hints:

  1. Java compiles source code into portable bytecode, which can execute through compatible Java Virtual Machines on different systems.
  2. Discuss portability, historical applets, security, networking libraries, dynamic loading, multithreading, and distributed or server-side applications.

1.4 Java Buzzwords

Definition

Java buzzwords are commonly used terms that describe the main design characteristics and capabilities of the Java programming language and runtime environment.


They summarize what Java was designed to provide: easier programming, object-oriented organization, reliability, concurrent execution, portability, managed execution, good runtime performance, networking support, and the ability to adapt while a program is running.

Detailed Explanation

1. Simple

Java is called simple because its designers kept much of the familiar syntax of C and C++ while removing or controlling several features that often increase complexity.

Examples include:

  • No exposed pointer arithmetic.
  • No manual memory deallocation for ordinary objects.
  • No C-style header files or preprocessor.
  • No direct multiple inheritance of classes.
  • Automatic garbage collection.

"Simple" does not mean that every Java program is easy. It means the language removes several low-level mechanisms that programmers would otherwise have to manage manually.

2. Object-Oriented

Java is strongly object-oriented. Programs are organized primarily around classes and objects. Its object-oriented model supports encapsulation, inheritance, polymorphism, and abstraction.

class Student {
    String name;

    void displayName() {
        System.out.println(name);
    }
}

Here, Student defines data and behavior together inside one class.

3. Robust

Robust means Java is designed to reduce common runtime failures and improve program reliability.

Java supports robustness through:

  • Strong type checking.
  • Automatic garbage collection.
  • Exception handling.
  • Array bounds checking.
  • Controlled object references rather than exposed pointer arithmetic.

4. Multithreaded

Multithreaded means one Java program can contain multiple threads of execution that make progress concurrently.

A thread is an independent path of execution inside a process. For example, a desktop application may use one thread for the interface while another performs a background operation.

Java provides language and library support for creating, coordinating, and synchronizing threads.

5. Architecture Neutral

Architecture neutral means Java's compiled representation is not designed for one particular processor architecture.

A Java compiler generates bytecode rather than instructions for only one processor family. The Java Virtual Machine on the destination system handles the machine-specific execution.

6. Interpreted

Java is traditionally described as interpreted because Java bytecode can be read and executed by the Java Virtual Machine at runtime.

Modern Java implementations use a hybrid approach. Bytecode may begin under an interpreter and frequently executed portions may later be compiled into native machine code by a Just-In-Time (JIT) compiler.

7. High Performance

High performance refers to Java's ability to execute frequently used code efficiently despite using a virtual machine.

The Just-In-Time compiler can identify heavily executed methods or code paths and compile them into optimized native machine instructions during program execution.

8. Distributed

Distributed means Java provides features suitable for programs whose components communicate across networked computers.

Java's standard libraries support network communication, web protocols, sockets, remote services, and related technologies used to construct distributed systems.

9. Dynamic

Dynamic means Java can load and link classes while a program is running instead of requiring every component to be permanently fixed before execution begins.

This supports extensible applications, frameworks, plug-in architectures, reflection, and runtime class loading.

Comparison of Java Buzzwords

BuzzwordMain Meaning
SimpleReduces several difficult low-level programming features.
Object-OrientedOrganizes programs around classes and objects.
RobustProvides mechanisms that improve reliability and error handling.
MultithreadedSupports multiple concurrent execution paths.
Architecture NeutralBytecode is not tied to one processor architecture.
InterpretedThe Java Virtual Machine can execute bytecode at runtime.
High PerformanceJust-In-Time compilation can convert frequently executed code to optimized native code.
DistributedProvides extensive support for network-based applications.
DynamicClasses and components can be loaded during execution.

Let's Clarify

The buzzwords describe different layers of Java. Simple and object-oriented describe how programmers write software. Robust describes reliability. architecture neutral describes portability. interpreted and high performance describe execution. multithreaded, distributed, and dynamic describe capabilities available while applications run.

Common Mistake

Architecture neutral and platform independent are related but not identical phrases. Architecture neutrality focuses on the compiled bytecode not targeting one processor instruction set. Platform independence is the broader result that allows a Java program to operate across systems with compatible Java runtimes.

Summary

  • Java buzzwords summarize the language's major design characteristics.
  • Simple, object-oriented, and robust describe programming structure and reliability.
  • Multithreaded and distributed describe support for concurrent and networked applications.
  • Architecture-neutral bytecode contributes to portability.
  • Interpreted execution and Just-In-Time compilation work together in modern Java runtimes.
  • Dynamic class loading allows programs to load components during execution.

Test Yourself

  1. Explain why Java is described as architecture neutral.
  2. How can Java be described as both interpreted and high performance?
  3. List any two Java Buzzwords. (October, 2023)

Hints:

  1. The compiler generates bytecode instead of code for one specific processor. A platform-specific Java Virtual Machine performs execution.
  2. The virtual machine can interpret bytecode and use Just-In-Time compilation to convert frequently executed code into optimized native instructions.
  3. Any two from the provided list, such as Simple and Robust, with brief meanings if explanation is requested.

1.5 Java Virtual Machine, Java Runtime Environment, and Java Development Kit

Definition

The Java Virtual Machine (JVM) executes Java bytecode, the Java Runtime Environment (JRE) provides the environment required to run Java applications, and the Java Development Kit (JDK) provides the tools required to develop, compile, and run Java programs.


These three terms describe different layers of the Java platform. The JVM is the execution engine. The JRE traditionally combines the JVM with runtime libraries. The JDK adds development tools such as the Java compiler.

Detailed Explanation

The conventional academic relationship is:

JDK → contains development tools + runtime environment

JRE → contains JVM + runtime libraries

JVM → loads, verifies, and executes Java bytecode

1. Java Virtual Machine (JVM)

The Java Virtual Machine is an abstract execution environment that runs compiled Java bytecode.

Its major responsibilities include:

  • Loading Java class files.
  • Checking bytecode for structural validity.
  • Managing runtime memory.
  • Executing bytecode.
  • Supporting garbage collection.
  • Providing runtime services to Java programs.
  • Using interpretation and Just-In-Time compilation where appropriate.

Main JVM Components

A detailed JVM implementation has several cooperating parts.

Class Loader

The class loader brings required class definitions into the Java Virtual Machine when they are needed.

The basic flow is:

Locate class → load class data → verify and prepare → make class available for execution

Bytecode Verifier

The bytecode verifier checks loaded bytecode for validity and helps prevent illegal operations from entering normal execution.

Runtime Data Areas

The Java Virtual Machine organizes memory into runtime areas. At an introductory level, the most useful distinctions are:

  • Heap: stores most dynamically created objects and arrays.
  • Java stacks: hold method-call frames, local variables, and intermediate method data for threads.
  • Method-related storage: stores class-level information used by the runtime.
  • Program counter information: tracks the current instruction for each executing thread.

Execution Engine

The execution engine performs the actual execution of bytecode. Depending on the Java Virtual Machine implementation, it can involve:

  • Interpreter: executes bytecode instructions during runtime.
  • Just-In-Time compiler: converts frequently executed bytecode into native machine code for faster repeated execution.
  • Garbage collector: reclaims memory occupied by objects that are no longer reachable by the program.

2. Java Runtime Environment (JRE)

The Java Runtime Environment is the traditional runtime package needed to execute Java applications.

Conceptually it includes:

  • The Java Virtual Machine.
  • Core Java class libraries.
  • Supporting runtime components.

The JRE is concerned with running Java software, not with providing a complete set of development tools.

In modern Java distributions, a separately installed general-purpose JRE is less central than it was historically, but the JRE concept remains useful for understanding the distinction between runtime components and development tools.

3. Java Development Kit (JDK)

The Java Development Kit is the complete development package used by Java programmers.

It provides the runtime capabilities plus development tools such as:

  • javac: the Java compiler.
  • java: the application launcher used to start Java programs.
  • javadoc: generates documentation from specially formatted source comments.
  • jar: packages Java classes and resources into Java Archive files.
  • Other debugging, inspection, packaging, and development utilities depending on the JDK distribution.

Architecture Relationship

ComponentPrimary RoleTypical ContentsMain User
JVMExecutes bytecodeClass loading, memory management, execution engine, garbage collectionRuntime system
JREProvides the Java runtime environmentJVM plus runtime libraries and supporting filesUser running Java software
JDKProvides Java development toolsRuntime components plus compiler and development utilitiesJava developer

Program Flow Through the Architecture

Programmer writes .java source file → JDK compiler javac creates .class bytecode → runtime loads the class → JVM verifies and executes bytecode → execution engine interprets or compiles instructions as needed

Let's Clarify

Consider a university computer lab. The JDK is like the full programming laboratory because it contains the tools needed to build software. The JRE is the equipment needed to use a finished Java application. The JVM is the machine inside that environment that actually performs the bytecode execution.

Common Mistake

The JDK, JRE, and JVM are not interchangeable names. The JVM executes bytecode. The JRE provides runtime support. The JDK provides development tools, including the compiler required to turn source code into bytecode.

Summary

  • The JVM is the engine that loads and executes Java bytecode.
  • The JRE traditionally consists of the JVM plus runtime libraries and supporting components.
  • The JDK provides the compiler and other development tools in addition to runtime capabilities.
  • The JVM manages class loading, runtime memory, execution, and garbage collection.
  • javac compiles source code while java starts a compiled Java application.
  • The conventional relationship is JDK contains JRE, and JRE contains JVM plus runtime support.

Test Yourself

  1. Differentiate the JVM, JRE, and JDK by their roles.
  2. Trace a Java program from source code to execution.
  3. Describe the architecture of JVM, JRE, and JDK. (Model Q)

Hints:

  1. JVM executes bytecode; JRE supplies the runtime environment; JDK supplies development tools and runtime capabilities.
  2. .java → javac → .class bytecode → class loading and verification → JVM execution.
  3. Explain the JDK/JRE/JVM containment relationship, then describe class loader, runtime memory, execution engine, interpreter, Just-In-Time compiler, and garbage collection.

1.6 Java Bytecode

Definition

Java bytecode is the platform-neutral intermediate instruction format generated by the Java compiler from Java source code and stored mainly in .class files.


Bytecode is not ordinary Java source code and is not normally the direct machine language of a physical processor. It is an intermediate form designed for the Java Virtual Machine.

Detailed Explanation

Suppose a file named Hello.java contains Java source code. When the compiler processes it:

Hello.java → javac → Hello.class

The Hello.class file contains bytecode representing the compiled class.

Why Bytecode Exists

If Java generated only processor-specific machine code, the same compiled file could not normally be used unchanged on every processor architecture. Bytecode introduces a portable intermediate layer.

The destination computer only needs a compatible Java Virtual Machine capable of understanding that bytecode and translating or executing it appropriately for its own hardware.

Significance of Bytecode

1. Platform Independence

The same compiled bytecode can be used on different systems with suitable Java Virtual Machine implementations.

2. Portability

Developers can distribute compiled class files without creating a separate source-to-native compilation for every supported operating system and processor combination.

3. Security and Verification

Before normal execution, the Java runtime can inspect bytecode for structural validity. This provides an additional controlled stage between compilation and execution.

4. Runtime Optimization

Because the Java Virtual Machine observes a program while it runs, it can identify frequently executed bytecode and compile selected parts into optimized native machine code using Just-In-Time compilation.

5. Common Execution Format

Bytecode gives Java implementations a common execution target. The compiler targets the Java Virtual Machine instruction set, while the JVM implementation handles platform-specific behavior.

RepresentationProduced ByUsed ByPlatform Dependency
Java source codeProgrammerJava compilerHuman-readable language source
Java bytecodeJava compilerJava Virtual MachineDesigned to be platform-neutral
Native machine instructionsRuntime compiler or native compilerPhysical processorArchitecture-specific

Let's Clarify

A video stored in a standard format can be played on many devices as long as each device has compatible software to decode that format. Java bytecode works on a related principle: the compiled program uses a common intermediate format, while each platform provides its own Java Virtual Machine implementation to execute that format.

Common Mistake

Bytecode is not the same as source code and is not usually the final native machine code executed directly by a physical processor. It is an intermediate instruction format intended for the Java Virtual Machine.

Summary

  • Java source code is compiled into bytecode stored mainly in .class files.
  • Bytecode targets the Java Virtual Machine rather than one specific physical processor.
  • Its main benefit is portability across systems with compatible Java runtimes.
  • Bytecode can be verified before execution.
  • Frequently executed bytecode can be converted into optimized native code at runtime.

Test Yourself

  1. Why does Java use an intermediate bytecode representation?
  2. How does bytecode contribute to Java's platform independence?
  3. What is the significance of bytecode? (March-April, 2023)

Hints:

  1. It separates source compilation from a particular physical processor and gives the Java Virtual Machine a common instruction format.
  2. The same .class bytecode can execute through compatible Java Virtual Machines implemented for different platforms.
  3. Mention portability, platform independence, verification, common JVM instruction format, and runtime optimization through Just-In-Time compilation.

1.7 Compilation Model and Interpretation Model

Definition

A compilation model translates program code into another executable representation before normal execution, while an interpretation model processes and executes program instructions through an interpreter during runtime.


Java combines both ideas. The source program is first compiled into bytecode. The Java Virtual Machine then executes that bytecode, often using both interpretation and Just-In-Time compilation.

Detailed Explanation

Traditional Compilation

In a traditional native compilation model:

Source code → native compiler → machine code → processor executes machine code

The resulting executable normally targets a specific operating system and processor architecture.

Traditional Interpretation

In a basic interpretation model:

Source or intermediate instructions → interpreter reads instruction → interpreter performs operation → next instruction is processed

The interpreter remains involved during program execution.

Java's Hybrid Model

Java normally uses two major stages:

Stage 1: Compilation

Java source code → Java compiler → bytecode

Stage 2: Runtime execution

Bytecode → Java Virtual Machine → interpretation and/or runtime native compilation → processor

Role of the Just-In-Time Compiler

Repeated interpretation of frequently executed code can add overhead. Modern Java Virtual Machines therefore use a Just-In-Time compiler.

A typical execution sequence is:

Load bytecode → begin execution → observe runtime behavior → identify frequently executed code → compile selected bytecode to native machine code → reuse optimized native code

This approach allows Java to retain portability at the bytecode level while improving runtime performance.

Comparison

FeatureNative CompilationInterpretationJava Model
Translation timeMainly before executionDuring executionSource compiled first, bytecode handled at runtime
OutputNative machine codeUsually no permanent native executable requiredBytecode first; selected code may become native at runtime
Portability of compiled formUsually platform-specificDepends on interpreter availabilityBytecode portable across compatible JVM implementations
Runtime optimizationPrimarily compiler-driven before launchUsually interpreter-drivenJVM can optimize using runtime information

Summary

  • Compilation translates code before normal execution.
  • Interpretation executes instructions through an interpreter during runtime.
  • Java first compiles source code into bytecode.
  • The JVM can interpret bytecode and use Just-In-Time compilation for frequently executed code.
  • Java's hybrid model combines portability with opportunities for runtime optimization.

Test Yourself

  1. Differentiate compilation from interpretation.
  2. Why is Java often described as using both compilation and interpretation?
  3. Explain the role of Just-In-Time compilation in Java.

Hints:

  1. Compilation translates code before execution; interpretation processes instructions during execution.
  2. javac compiles source to bytecode, then the JVM executes bytecode using interpretation and runtime compilation.
  3. The Just-In-Time compiler converts frequently executed bytecode into native code to reduce repeated interpretation and improve performance.

1.8 Platform Independence

Definition

Platform independence means a compiled Java program can run on different hardware and operating systems without recompiling the original source for each platform, provided a compatible Java Virtual Machine is available.


Java achieves this by compiling source code into bytecode rather than directly into the native instruction set of one computer.

Detailed Explanation

A platform generally refers to the combination of hardware architecture and operating-system environment on which software runs.

In many traditional compiled languages:

Source code → compiler for Platform A → executable for Platform A

Moving the same program to Platform B may require another compilation process, and sometimes source-level adjustments.

Java inserts the Java Virtual Machine between bytecode and the underlying platform:

Java source → bytecode → JVM for Windows → Windows machine

Java source → same bytecode → JVM for Linux → Linux machine

Java source → same bytecode → JVM for macOS → macOS machine

Write Once, Run Anywhere

Java's portability idea is often summarized by the phrase Write Once, Run Anywhere. The key point is not that every possible environmental difference disappears. It means Java bytecode is designed to run through compatible Java runtime implementations on supported platforms without recompiling the application's source for each processor architecture.

How Platform Independence Is Achieved

Programmer writes platform-neutral Java source → compiler creates platform-neutral bytecode → each platform provides its own JVM implementation → JVM translates or executes bytecode according to the local system

What Is Platform-Dependent?

The Java program's bytecode is designed to be portable, but the JVM implementation itself is platform-specific. A Windows JVM and a Linux JVM must interact differently with their respective operating systems and hardware.

Common Mistake

"Java is platform independent" does not mean every component of Java is identical on every machine. The bytecode provides the portable layer. The JVM underneath it must be implemented for the particular platform on which it runs.

Summary

  • Platform independence allows Java bytecode to run across different supported systems.
  • The compiler generates bytecode instead of one platform's native machine code.
  • Each platform supplies a compatible Java Virtual Machine.
  • The bytecode is portable, while the JVM implementation is platform-specific.
  • This model is commonly summarized as Write Once, Run Anywhere.

Test Yourself

  1. Explain how Java achieves platform independence.
  2. If Java is platform independent, why do different operating systems need different JVM implementations?

Hints:

  1. Java source is compiled to portable bytecode. A compatible JVM on each platform executes that bytecode.
  2. The JVM communicates with the local operating system and processor, so its implementation must match the platform even though the bytecode remains portable.

1.9 Writing, Compiling, and Running a Simple Java Program

Definition

Java program development involves writing source code in a .java file, compiling it into bytecode with a Java compiler, and executing the resulting class through the Java runtime.


The smallest useful Java program demonstrates the basic structure shared by many programs: a class, a main method, statements, compilation, and execution.

Detailed Explanation

A Simple Java Program

public class HelloJava {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Understanding the Program

  • public class HelloJava: declares a class named HelloJava.
  • public static void main(String[] args): declares the standard entry method used by the Java launcher to begin a basic application.
  • System.out.println(...): prints text to the standard output stream.
  • Curly braces: define the body of the class and method.
  • Semicolon: terminates the output statement.

Step 1: Save the Source File

Save the program as:

HelloJava.java

When a public top-level class is named HelloJava, the source filename must match that public class name.

Step 2: Compile

javac HelloJava.java

If compilation succeeds, the compiler produces:

HelloJava.class

The class file contains Java bytecode.

Step 3: Run

java HelloJava

The Java launcher starts the runtime, loads HelloJava, locates its main method, and begins execution.

Output:

Hello, Java!

Complete Development Sequence

Write source → save .java file → compile with javac → correct compilation errors if any → obtain .class bytecode → run using java → JVM executes program → observe output

Common Compile-Time Error Example

public class Demo {
    public static void main(String[] args) {
        System.out.println("Hello")
    }
}

The missing semicolon causes compilation to fail. The compiler reports the error, and the programmer must correct the source before normal execution.

Runtime Error Concept

A program can compile successfully but encounter a problem while running. Such problems are called runtime errors or may appear as exceptions.

For example:

public class Demo {
    public static void main(String[] args) {
        int result = 10 / 0;
        System.out.println(result);
    }
}

The source can compile, but integer division by zero causes a runtime exception when that statement executes.

Summary

  • A Java source file normally uses the .java extension.
  • javac compiles source code into bytecode stored in .class files.
  • The java launcher starts the runtime and executes the requested class.
  • The main method provides the usual entry point for a basic Java application.
  • Compile-time errors are detected during compilation, while runtime errors occur during execution.

Test Yourself

  1. Write the sequence required to compile and execute HelloJava.java.
  2. What is the purpose of the main method in a basic Java application?
  3. Differentiate a source file from a class file.

Hints:

  1. javac HelloJava.java creates bytecode, then java HelloJava starts and executes the class.
  2. It is the standard entry method from which the Java launcher begins execution of a basic application.
  3. A .java file contains source code; a .class file contains compiled Java bytecode.

1.10 Using the Command Line and an Integrated Development Environment

Definition

The command line allows Java tools to be run by typing commands directly, while an Integrated Development Environment (IDE) provides a graphical environment that combines editing, compilation, execution, debugging, and project management tools.


Both methods ultimately rely on the same Java language and runtime concepts. The command line exposes the steps directly, while an IDE automates many of them through menus, buttons, project settings, and editor features.

Detailed Explanation

Using Java from the Command Line

Assume the source file is saved in a folder containing:

HelloJava.java

Open a terminal or command prompt and move to that folder. Then compile:

javac HelloJava.java

After successful compilation:

java HelloJava

Checking the Installed Java Tools

The following command can display the installed Java runtime or launcher version:

java -version

The compiler version can normally be checked using:

javac -version

Typical Command-Line Workflow

Create file → open terminal → navigate to folder → compile with javac → inspect compiler messages → run with java → inspect program output

Using an Integrated Development Environment

An Integrated Development Environment provides a single application in which a developer can create a project, write source code, compile it, run it, and debug problems.

A typical IDE workflow is:

Create Java project → create Java class → write source code → build or compile → run project/class → view console output → debug if needed

Common IDE Capabilities

  • Source editor: provides code editing, indentation, and syntax assistance.
  • Build integration: invokes compilers and build tools.
  • Run configuration: specifies which class or project should execute.
  • Debugger: allows execution to pause at breakpoints and lets programmers inspect values.
  • Project management: organizes source files, packages, libraries, and resources.
  • Error highlighting: identifies many syntax and type errors during editing.

Command Line vs IDE

FeatureCommand LineIDE
InterfaceText commandsGraphical development environment
CompilationExplicit javac commandUsually handled through build/run actions
ExecutionExplicit java commandUsually started through Run action
DebuggingRequires command-line tools or additional setupUsually has integrated debugger
Learning execution flowShows compile and run stages directlyAutomates many stages
Large project managementPossible but more manualUsually provides extensive project features

Summary

  • Java can be developed and executed from either command-line tools or an IDE.
  • The command line exposes compilation and execution as separate commands.
  • An IDE integrates editing, building, execution, debugging, and project management.
  • javac is used for compilation and java is used to launch a Java class.
  • Both approaches produce and execute the same kind of Java bytecode.

Test Yourself

  1. Compare Java development from the command line with development in an IDE.
  2. Which commands are used to compile and run a Java class from the command line?

Hints:

  1. The command line requires explicit commands; an IDE integrates editing, compiling, running, debugging, and project organization in one interface.
  2. javac FileName.java compiles; java ClassName launches the compiled class.

1.11 Object-Oriented Programming Paradigm

Definition

Object-Oriented Programming (OOP) is a programming paradigm that organizes software around objects that combine data with the operations that act on that data.


Instead of treating a program only as a long sequence of instructions, OOP models important entities as objects. A student, bank account, employee, vehicle, or product can be represented using a class that defines its data and behavior.

Detailed Explanation

Class

A class is a blueprint or definition from which objects are created.

class Student {
    String name;
    int semester;

    void displayInfo() {
        System.out.println(name + " " + semester);
    }
}

Object

An object is an instance of a class. It has its own state stored in fields and can perform behavior defined by methods.

Student s1 = new Student();
s1.name = "Aarav";
s1.semester = 3;
s1.displayInfo();

Here, s1 refers to an object created from the Student class.

Four Core OOP Principles

1. Encapsulation

Encapsulation means combining related data and methods inside a class while controlling how that data can be accessed or modified.

Java supports access control through modifiers such as private, protected, and public.

class BankAccount {
    private double balance;

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}

The field balance is private, so outside code cannot directly change it using unrestricted field access. The class provides controlled operations such as deposit().

Why Encapsulation Is Useful

  • Protects internal object state.
  • Allows validation before changing data.
  • Reduces dependence on implementation details.
  • Makes classes easier to maintain and modify.

2. Inheritance

Inheritance allows one class to acquire accessible data and behavior from another class and add or specialize its own features.

The existing class is commonly called the superclass, and the class that inherits from it is the subclass.

class Person {
    String name;

    void displayName() {
        System.out.println(name);
    }
}

class Student extends Person {
    int semester;
}

Student extends Person, so a Student object can use inherited accessible members of Person while adding student-specific information.

Why Inheritance Is Useful

  • Supports code reuse.
  • Represents "is-a" relationships.
  • Allows common behavior to be defined in a parent class.
  • Provides a basis for runtime polymorphism.

3. Polymorphism

Polymorphism means one common interface, method name, or reference type can represent different behaviors depending on the actual object or arguments involved.

One important Java form is method overriding:

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Meow");
    }
}

A superclass reference can refer to different subclass objects:

Animal a1 = new Dog();
Animal a2 = new Cat();

a1.sound();
a2.sound();

Output:

Bark
Meow

The same method call sound() produces behavior appropriate to the actual object.

Forms of Polymorphism in Java

  • Compile-time polymorphism: commonly associated with method overloading.
  • Runtime polymorphism: commonly associated with method overriding and dynamic method dispatch.

4. Abstraction

Abstraction means exposing the essential behavior of something while hiding unnecessary implementation details.

A user can call a method without needing to know every internal step used to perform the operation.

Java supports abstraction using classes, abstract classes, methods, and interfaces.

abstract class Shape {
    abstract double area();
}

class Rectangle extends Shape {
    double width;
    double height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    double area() {
        return width * height;
    }
}

The abstract class states that every concrete shape must provide an area() operation, while each subclass decides how the area is calculated.

Relationship Among the Four Principles

Encapsulation protects an object's internal state → abstraction exposes only the essential operations → inheritance allows related classes to reuse and specialize behavior → polymorphism allows common operations to behave according to the actual object

Comparison of OOP Principles

PrincipleMain IdeaJava MechanismExample
EncapsulationProtect and organize internal stateClasses, access modifiers, methodsPrivate bank balance changed through deposit method
InheritanceCreate a specialized class from an existing classextendsStudent extends Person
PolymorphismSame operation can have different behaviorOverloading, overriding, dynamic dispatchDifferent subclasses implement sound()
AbstractionExpose essentials while hiding detailsClasses, abstract classes, interfacesShape defines an area operation

Let's Clarify

Consider a ride-booking application. A vehicle object stores its own data, which demonstrates encapsulation. Car and Bike can inherit common features from Vehicle. A method such as calculateFare() can behave differently for different vehicle types, which demonstrates polymorphism. The passenger only requests a ride and sees a fare without needing to know every internal pricing calculation, which demonstrates abstraction.

Common Mistake

Encapsulation and abstraction are related but different. Encapsulation focuses on bundling state and behavior and controlling access. Abstraction focuses on presenting essential behavior while hiding unnecessary implementation detail.

Summary

  • OOP organizes programs around classes and objects.
  • Encapsulation combines data with methods and controls access to internal state.
  • Inheritance allows a subclass to reuse and specialize features of a superclass.
  • Polymorphism lets common operations produce behavior appropriate to different objects.
  • Abstraction exposes essential operations while hiding unnecessary implementation details.
  • The four principles work together to make software modular, reusable, and easier to maintain.

Test Yourself

  1. Define Object-Oriented Programming and explain its four main principles.
  2. Differentiate encapsulation from abstraction.
  3. How does method overriding demonstrate runtime polymorphism?

Hints:

  1. Define OOP around objects; explain encapsulation, inheritance, polymorphism, and abstraction with one example each.
  2. Encapsulation protects and controls state inside a class; abstraction hides unnecessary implementation and presents essential behavior.
  3. A superclass reference can refer to different subclass objects, and the overridden method corresponding to the actual object runs at runtime.

1.12 Using Command Line Arguments

Definition

Command line arguments are values supplied to a Java program when it is launched from the command line and received by the program through the String[] args parameter of the main method.


They allow information to be passed into a program without asking for interactive keyboard input after the program starts.

Detailed Explanation

The usual Java entry method is:

public static void main(String[] args)

args is an array of String values. Each command-line argument becomes one element of this array.

Example: Displaying Arguments

public class ShowArgs {
    public static void main(String[] args) {
        System.out.println(args[0]);
        System.out.println(args[1]);
    }
}

Compile:

javac ShowArgs.java

Run:

java ShowArgs Nepal Java

The array contains:

args[0] = "Nepal"
args[1] = "Java"

Output:

Nepal
Java

Argument Indexing

Java arrays use zero-based indexing:

CommandArray ElementValue
java Demo Ram 23 BCAargs[0]"Ram"
args[1]"23"
args[2]"BCA"

All Arguments Arrive as Strings

Even when the user types digits, command-line arguments enter the program as strings.

For numeric calculations, the string must be converted.

public class AddArgs {
    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);

        System.out.println(a + b);
    }
}

Run:

java AddArgs 10 20

Output:

30

Checking the Number of Arguments

Trying to access an array element that does not exist causes an error during execution. Programs can inspect args.length first.

public class Greeting {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("No name provided.");
            return;
        }

        System.out.println("Hello " + args[0]);
    }
}

Processing Every Argument

public class ListArgs {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

Common Mistake

The text "10" received through args[0] is a String, not an int. Numeric command-line values must be parsed before arithmetic operations that require numeric types.

Summary

  • Command-line arguments are passed when the Java application is launched.
  • They are received through the String[] args parameter of main.
  • The first argument is stored at index 0.
  • All command-line arguments initially arrive as strings.
  • Methods such as Integer.parseInt() can convert numeric text to numeric values.
  • args.length tells the program how many arguments were supplied.

Test Yourself

  1. What are command-line arguments and where are they stored in a Java program?
  2. What does args[1] represent in java Demo A B C?
  3. Why is Integer.parseInt() needed when adding numeric command-line arguments?

Hints:

  1. They are values supplied at launch time and stored as elements of the String[] args array.
  2. args[1] contains "B".
  3. Command-line arguments arrive as strings, so numeric text must be converted before integer arithmetic.

1.13 Reading Input with the Scanner Class

Definition

The Scanner class is a Java utility class used to read and convert input from sources such as the keyboard, strings, or files.


For beginner console programs, Scanner is commonly connected to System.in, which represents the standard input stream. The program can then read integers, decimal values, words, and complete lines.

Detailed Explanation

The Scanner class belongs to the java.util package. Before using it by its short class name, import it:

import java.util.Scanner;

Create a Scanner connected to keyboard input:

Scanner input = new Scanner(System.in);

Here:

  • Scanner: class used for scanning input.
  • input: variable that refers to the Scanner object.
  • new Scanner(System.in): creates a Scanner that reads from standard input.

Basic Example

import java.util.Scanner;

public class StudentInput {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = input.nextLine();

        System.out.print("Enter your age: ");
        int age = input.nextInt();

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

        input.close();
    }
}

Common Scanner Methods

MethodPurposeExample InputReturned Type
next()Reads the next token or wordJavaString
nextLine()Reads the remainder of the current line as textObject Oriented JavaString
nextInt()Reads an integer25int
nextLong()Reads a long integer9000000000long
nextFloat()Reads a floating-point value3.5float
nextDouble()Reads a double-precision value98.75double
nextBoolean()Reads a Boolean valuetrueboolean

Example: Reading Two Numbers

import java.util.Scanner;

public class AddNumbers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int first = input.nextInt();

        System.out.print("Enter second number: ");
        int second = input.nextInt();

        int sum = first + second;

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

        input.close();
    }
}

Possible interaction:

Enter first number: 12
Enter second number: 8
Sum = 20

next() vs nextLine()

next() normally reads one token separated by whitespace. nextLine() reads text up to the end of the line.

For input:

Ram Bahadur

next() reads:

Ram

nextLine() can read:

Ram Bahadur

The nextInt() and nextLine() Issue

A common issue appears when a token-reading method such as nextInt() is followed immediately by nextLine().

Scanner input = new Scanner(System.in);

System.out.print("Enter age: ");
int age = input.nextInt();

System.out.print("Enter full name: ");
String name = input.nextLine();

After nextInt() reads the number, the line-ending character can remain waiting in the input stream. The following nextLine() may consume that remaining line ending and return an empty string.

One Common Fix

System.out.print("Enter age: ");
int age = input.nextInt();
input.nextLine();

System.out.print("Enter full name: ");
String name = input.nextLine();

The additional nextLine() consumes the remaining end of the previous input line before the program reads the actual name.

Closing the Scanner

input.close();

The close() method closes the Scanner and its underlying input source. In a small program where keyboard input is no longer needed, this is normally placed near the end of main.

Let's Clarify

Scanner behaves like a reader standing in front of an input stream. A method such as nextInt() tells the reader to take the next token and interpret it as an integer. next() takes one word-like token. nextLine() takes everything remaining until the line ends.

Common Mistake

When nextInt(), nextDouble(), or another token-oriented method is followed by nextLine(), the pending line ending can cause nextLine() to return immediately. Consuming the remaining line first prevents this common input problem.

Summary

  • Scanner is used to read input and convert tokens into Java values.
  • Keyboard input is commonly read using new Scanner(System.in).
  • nextInt(), nextDouble(), and similar methods read typed numeric values.
  • next() reads one token while nextLine() reads to the end of a line.
  • Mixing token-reading methods with nextLine() requires attention to leftover line endings.
  • close() closes the Scanner when its input source is no longer needed.

Test Yourself

  1. Write the statements required to create a Scanner for keyboard input and read an integer.
  2. Differentiate next() and nextLine().
  3. What is the task of Scanner class? (March-April, 2023 / October, 2023)

Hints:

  1. Import java.util.Scanner, create Scanner input = new Scanner(System.in);, then call input.nextInt().
  2. next() reads one whitespace-delimited token; nextLine() reads characters through the end of the current line.
  3. Scanner reads input from sources such as System.in and provides methods that parse the input into strings, integers, floating-point values, Boolean values, and other supported types.

1.14 Writing Output with System.out

Definition

System.out is Java's standard output stream, commonly used to display text and values on the console.


Java provides methods such as print(), println(), and printf() through System.out. They differ mainly in line handling and formatting capability.

Detailed Explanation

Consider:

System.out.println("Hello");

The statement contains three important parts:

  • System: a standard Java class containing system-related facilities.
  • out: the standard output stream associated with System.
  • println(): a method that writes a value and then ends the line.

print()

print() outputs a value without automatically moving to a new line afterward.

System.out.print("Hello ");
System.out.print("Java");

Output:

Hello Java

println()

println() prints a value and then terminates the current line.

System.out.println("Hello");
System.out.println("Java");

Output:

Hello
Java

printf()

printf() produces formatted output using a format string and replacement values.

String name = "Sita";
int age = 21;

System.out.printf("Name: %s, Age: %d%n", name, age);

Output:

Name: Sita, Age: 21

Common Format Specifiers

SpecifierTypical UseExample
%sString value"Java"
%dDecimal integer25
%fFloating-point value3.14159
%cCharacter'A'
%bBoolean-style formattingtrue
%nPlatform-appropriate line separatorNew line

Formatting Decimal Places

double price = 123.4567;

System.out.printf("Price = %.2f%n", price);

Output:

Price = 123.46

%.2f requests a floating-point value displayed with two digits after the decimal point.

Printing Variables and Expressions

int a = 10;
int b = 20;

System.out.println(a);
System.out.println(a + b);
System.out.println("Sum = " + (a + b));

Output:

10
30
Sum = 30

String Concatenation

The + operator joins strings with values when one side of the operation is already a string.

String name = "Hari";
int semester = 3;

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

Parentheses and Expression Order

Consider:

System.out.println("Total = " + 10 + 20);

Output:

Total = 1020

Once string concatenation begins, the values are joined as text from left to right.

To perform addition first:

System.out.println("Total = " + (10 + 20));

Output:

Total = 30

Comparison of Output Methods

MethodAutomatic New LineFormatted OutputTypical Use
print()NoNo format stringKeep following output on the same line
println()YesNo format stringDisplay ordinary lines of output
printf()Only when requested in formatYesControl numeric and text formatting

Common Mistake

"Sum = " + 10 + 20 produces text equivalent to "Sum = 1020", not "Sum = 30". Use "Sum = " + (10 + 20) when the arithmetic must happen before string concatenation.

Summary

  • System.out represents Java's standard output stream.
  • print() displays output without automatically ending the line.
  • println() displays output and then ends the line.
  • printf() supports formatted output using format specifiers.
  • Variables, expressions, and strings can be combined in output statements.
  • Parentheses may be necessary to ensure arithmetic occurs before string concatenation.

Test Yourself

  1. Differentiate print(), println(), and printf().
  2. What does %.2f mean in a printf() format string?
  3. What is the output of System.out.println("Value = " + 5 + 6);?

Hints:

  1. print() stays on the current line; println() adds a line break; printf() applies format specifications.
  2. Display a floating-point value with two digits after the decimal point.
  3. Value = 56, because string concatenation proceeds from left to right after the string appears.

Exam Questions

  1. List the Key Aspects of Java's Impact on the Internet. (Model Q)
  2. Describe the architecture of JVM, JRE, and JDK. (Model Q)
  3. What is the significance of bytecode? (March-April, 2023)
  4. What is the task of Scanner class? (March-April, 2023 / October, 2023)
  5. List any two Java Buzzwords. (October, 2023)

Whole Chapter Summary

The Creation of Java

Java was created at Sun Microsystems as a portable, reliable language suitable for different types of systems. It began as Oak and developed into Java, using bytecode and a managed runtime to reduce dependence on specific hardware.

Java's Lineage and Influence

Java inherited much of its syntax from C and many object-oriented ideas from C++. It removed or restricted several low-level features while emphasizing managed memory, portability, standard libraries, and runtime safety.

Java's Impact on the Internet

Java's bytecode model allowed compiled programs to move across heterogeneous networked systems. Its early applets demonstrated portable downloadable programs, while networking libraries and server-side technologies supported large Internet and distributed applications.

Java Buzzwords

Java is described as Simple, Object-Oriented, Robust, Multithreaded, Architecture Neutral, Interpreted, High Performance, Distributed, and Dynamic. Together these terms summarize its design and runtime capabilities.

JVM, JRE, and JDK

The JVM executes bytecode. The JRE traditionally provides the JVM and runtime libraries. The JDK provides the compiler and other development tools in addition to the components needed to run Java programs.

Bytecode

Bytecode is the platform-neutral intermediate form generated by the Java compiler. The same bytecode can execute on different systems through compatible Java Virtual Machines.

Compilation and Interpretation

Java source is compiled to bytecode before execution. At runtime, the Java Virtual Machine can interpret that bytecode and compile frequently executed portions into optimized native instructions using Just-In-Time compilation.

Platform Independence

Java achieves platform independence by separating portable bytecode from the platform-specific JVM. The bytecode stays the same while each operating system uses a JVM implementation designed for that platform.

Writing, Compiling, and Running Java Programs

A Java program is written in a .java source file, compiled with javac into a .class file, and launched using the java command or equivalent IDE controls.

Command Line and IDE

The command line exposes compilation and execution as explicit operations. An Integrated Development Environment combines source editing, compilation, execution, debugging, and project management into one application.

Object-Oriented Programming

OOP organizes software around classes and objects. Encapsulation protects state, inheritance reuses and specializes behavior, polymorphism supports different behavior through common operations, and abstraction hides unnecessary implementation details.

Command Line Arguments

Values supplied when a Java program starts are received as strings through String[] args. Numeric text must be converted to numeric types before numeric calculations.

Scanner Input

The Scanner class reads and converts input from sources such as System.in. Methods such as nextInt(), next(), and nextLine() are used for different forms of input.

System.out Output

System.out provides standard console output. print() remains on the same line, println() ends the line, and printf() supports formatted output.

Key Formulas and Points Sheet

Rule / SequenceMeaning
Java source → compiler → bytecode → JVM → executionCore Java compilation and execution model.
JDK → JRE → JVMConventional conceptual containment: development kit includes runtime capabilities, and runtime includes the virtual machine and supporting libraries.
javac FileName.javaCompiles a Java source file into bytecode.
java ClassNameLaunches the compiled Java class.
String[] argsReceives command-line arguments as strings.
Integer.parseInt(text)Converts integer-form text into an int.
new Scanner(System.in)Creates a Scanner connected to standard keyboard input.
next()Reads the next token.
nextLine()Reads through the end of the current input line.
nextInt()Reads an integer token.
System.out.print()Writes output without an automatic line break.
System.out.println()Writes output followed by a line break.
System.out.printf()Writes output according to a format string.

Last-Minute Revision Sheet

ConceptTrigger PhraseRecall Cue
Java creationSun MicrosystemsJames Gosling, Oak, 1995, portability
Java lineageC → C++ → JavaC-style syntax + object-oriented design + managed runtime
Internet impactPortable network softwareBytecode, security, networking, historical applets, servers
SimpleLess low-level complexityNo exposed pointer arithmetic, automatic memory management
Object-OrientedClasses + objectsData and methods together
RobustReliabilityType checking, exceptions, bounds checking, garbage collection
MultithreadedConcurrent pathsMultiple threads in one process
Architecture NeutralNot one processorBytecode targets JVM
InterpretedRuntime executionJVM processes bytecode
High PerformanceJITHot bytecode → optimized native code
DistributedNetworked componentsNetworking and remote communication
DynamicRuntime loadingClasses loaded as needed
JVMExecution engineLoads + verifies + executes bytecode
JRERuntime environmentJVM + runtime libraries
JDKDeveloper toolkitCompiler + runtime + development tools
BytecodePortable intermediate code.class
Platform independenceSame bytecodeDifferent platform-specific JVMs
Compilejavac.java → .class
RunjavaClass → JVM execution
EncapsulationProtect statePrivate data + controlled methods
InheritanceReuse / specializeextends
PolymorphismOne interface, many behaviorsOverloading + overriding
AbstractionHide unnecessary detailsExpose essential operations
Command-line argumentString[] argsArguments begin at args[0]
ScannerInputnew Scanner(System.in)
next()One tokenStops at whitespace
nextLine()Whole lineReads to line ending
System.outOutputprint, println, printf
Views: …
TUpapers.com logo tupapers.com
  • Privacy Policy

  • Contact Us

  • Terms

  • Pricing

  • SEEpapers.com

TUpapers on Facebook
TUpapers on Instagram
Contact TUpapers on WhatsApp Contact TUpapers on WhatsApp
TUpapers subreddit on Reddit

Courses

  • BBA

  • BCA

  • BIT

  • CSIT

  • BBS

  • BHM

  • BBM

  • BITM

  • BTTM

  • BA

  • BE

  • BSW

© 2026 tupapers.com. All rights reserved.